Execute task in background in WPF application

c#, multithreading, tap, task-parallel-library, wpf

Solution

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.

Problem

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 - not block the UI thread - provide progress reporting - be cancelable - support multithreading

Original source

Related problems