Execute task in background in WPF application

Deadly 提交于 2019-11-26 02:15:03

问题


Example

private void Start(object sender, RoutedEventArgs e)
{
    int progress = 0;
    for (;;)
    {
        System.Threading.Thread.Sleep(1);
        progress++;
        Logger.Info(progress);
    }
}

What is the recommended approach (TAP or TPL or BackgroundWorker or Dispatcher or others) if I want Start() to

  1. not block the UI thread
  2. provide progress reporting
  3. be cancelable
  4. support multithreading

回答1:


With .NET 4.5 (or .NET 4.0 + Microsoft.Bcl.Async), the best way is to use Task-based API and async/await. It allows to use the convenient (pseudo-)sequential code workflow and have structured exception handling.

Example:

private async void Start(object sender, RoutedEventArgs e)
{
    try
    {
        await Task.Run(() =>
        {
            int progress = 0;
            for (; ; )
            {
                System.Threading.Thread.Sleep(1);
                progress++;
                Logger.Info(progress);
            }
        });
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

More reading:

How to execute task in the WPF background while able to provide report and allow cancellation?

Async in 4.5: Enabling Progress and Cancellation in Async APIs.

Async and Await.

Async/Await FAQ.




回答2:


The best way to do this is by using a BackgroundWorker.

The reason I point this one out is it is specially designed to process work in the background while leaving the UI thread available and responsive. It also has built in Progress notifications and supports Cancellation.

I suggest looking at a few examples of a the BackgroundWorker.

Now when you start looking into the background worker there is one point Cancellation that you will have to dig deeper into. Setting the cancel property of a background worker doesnt cancel the background worker, this just raises a flag for your running method to interogate at regular intervals and gracefully stop processing.

Here is one of my posts from awhile ago talking about cancelling a background worker https://stackoverflow.com/a/20941072/1397504

Finally. Asyncronous does not mean multi-core or even multi-thread. (WIKI)




回答3:


You can execute an operation on a separate thread in WPF using the BackgroundWorker Class.

check this example How to use WPF Background Worker

And read about the class on MSDN here http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx



来源:https://stackoverflow.com/questions/21326601/execute-task-in-background-in-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!