Alex Rivera | Logout

Support of progress reporting and incremental results in .NET 4.0 "Task Parallel Library"

Asked 2009-10-08T05:20:17.220
15

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 task scheduling, exception handling and cancellation.

But I don't find any references to progress reporting and sending incremental results from tasks. These 2 things seem too important to ignore. Can you throw some light on how to handle these in Task Parallel Library or refer some articles which explains them?

Edit
Report

2 Answers

8

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<string>.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.

answered 2011-12-15T10:03:22.553
2

The TPL isn't particularly oriented toward UI support, you can (still) use a BackgroundWorker for that. As for sending or processing intermediate results, there are new collectionclasses (ConcurrentQueue) to support that.

answered 2009-10-08T08:00:02.443

Your Answer