Raising event after Parallel.For completes job
After pressing button following function is called.
Task.Factory.StartNew(() =>
{
Parallel.For(0, cyclesCount, i => DoWork(i));
if (OnJobCompleted != null)
OnJobCompleted(this, EventArgs.Empty);
});
Further in code there is
void ladder_OnJobCompleted(object sender, EventArgs args)
{
txbDebug.Text = "completed";
}
I know
开发者_开发技巧txbDebug.Text = "completed";
has to be Invoked, beacause I'm raising event on different thread. But I can't figure out, how to Invoke it. This event is situated in wpf form.
Use the Dispatcher
txbDebug.Dispatcher.Invoke(new Action(() =>
{
txbDebug.Text = "completed";
}));
I do not expect you to want to use the new Async CTP, but if you are curious how this would be done with the new async
and await
keywords proposed for C# 5 then consider the following example. It really does not get any more elegant than this.
void async YourButton_Click(object sender, RoutedEventArgs args)
{
txbDebug.Text = await Task<string>.Factory.StartNew(
() =>
{
Parallel.For(0, cyclesCount, i => DoWork(i));
return "complete";
});
}
精彩评论