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

后端 未结 5 648
有刺的猬
有刺的猬 2020-12-29 07:49

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

5条回答
  •  清酒与你
    2020-12-29 08:45

    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.

提交回复
热议问题