I know that Task Parallel Library is still in Beta and there are likely to be less resources available but from whatever I have read, library gives very special treatment to
This is one of my top search result and still no example for progress in Task Parallel Library right here...
Today I just came across TPL because I want to develop new multithreaded application but without using BackgroundWorker (because I read somewhere about task with nice code before)
I compile the example from @Stephen Cleary answer, his link quite complicated for to look for progress, and some other websites.
This is the very simple example to how to do Progress and Completed with UI thread safe way:
TaskScheduler currentTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
// loop for about 10s with 10ms step
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(10);
Task.Factory.StartNew(() =>
{
// this is a task created each time you want to update to the UI thread.
this.Text = i.ToString();
}, CancellationToken.None, TaskCreationOptions.None, currentTaskScheduler);
}
return "Finished!";
})
.ContinueWith(t =>
{
// this is a new task will be run after the main task complete!
this.Text += " " + t.Result;
}, currentTaskScheduler);
The code will display 1 to 1000 within 10s and then append a " Finish!" string in the windows form title bar. You can see that the TaskScheduler is the tricky way to create UI thread safe update because I think the task scheduled to be run on main thread.