Igor Popov
Igor Popov

Reputation: 10103

When to use asynchronous programming with delegates?

They seem to be doing the same thing, but I don't know when I'm supposed to use tasks and when normal delegates.

Consider the example below:

private async void Button_Click(object sender, RoutedEventArgs e) {
    UseDelegates();
    // await UseTasks();
}

private void UseDelegates() {
    Action action = () => {
        Thread.Sleep(TimeSpan.FromSeconds(2));
    };

    var result = action.BeginInvoke(unusedResult => {
        MessageBox.Show("Used delegate.BeginInvoke!");
    }, null);
    action.EndInvoke(result);
}

private async Task UseTasks() {
    await Task.Run(() => {
        Thread.Sleep(TimeSpan.FromSeconds(2));
    });
    MessageBox.Show("Used await with tasks!");
}

Upvotes: 0

Views: 348

Answers (2)

mm8
mm8

Reputation: 169150

There is no truly asynchronous work being done in your example. It seems like the only thing you want to do is to offload some synchronous work to a background thread in order to keep the UI thread responsive during the time it takes for the synchronous method - Thread.Sleep in this case - to complete.

As stated on MSDN; starting with the .NET Framework 4, the Task Parallel Library (TPL) is the preferred way to write multithreaded and parallel code. That's what your UseTasks() method does, i.e. it uses Task.Run to schedule the call to Thread.Sleep on a thread pool thread using the TPL's default task scheduler.

The BeginInvoke/EndInvoke pattern is known as the Asynchronous Programming Model (APM). This pattern is no longer recommended for new development as stated here.

So to answer your questions, you are generally "supposed to use tasks" when offloading work to a background thread in .NET 4+ applications.

Upvotes: 1

tigerswithguitars
tigerswithguitars

Reputation: 2547

In the example you have given. I would use Task every time. The library and syntax has been created with the very aim of getting rid of BeginInvoke and EndInvoke type patterns.

The only time you probably don't want to use Task over an older library is in desktop apps that use BackgroundWorker, which is specifically for running long running background work, that wants to report progress easily to the UI thread. This sort of things isn't as elegant with tasks.

Upvotes: 1

Related Questions