PeteGO
PeteGO

Reputation: 5791

async Task is freezing the UI

I have a method like this:

private async Task DoSomething()
{
    // long running work here.
}

When I call the method like this it blocks the UI:

Task t = DoSomething();

I have to do one of these to make it non-blocking:

Task t = new Task(() => DoSomething());
t.Start();

// Or

Task t = Task.Factory.StartNew(() => DoSomething());

So what is the point of async / await when you can just use Tasks as they were in framework 4 and use Task.Wait() in place of await?

EDIT: I understand all of your answers - but none really address my last paragraph. Can anyone give me an example of Task based multi-threading where async / await improves the readability and/or flow of the program?

Upvotes: 6

Views: 8794

Answers (3)

Stephen Cleary
Stephen Cleary

Reputation: 456507

async methods begin their execution synchronously. async is useful for composing asynchronous operations, but it does not magically make code run on another thread unless you tell it to.

You can use Task.Run to schedule CPU-bound work to a threadpool thread.

See my async / await intro post or the async FAQ for more information.

Upvotes: 2

James Manning
James Manning

Reputation: 13579

Without the actual code, it's hard to tell you what's going on, but you can start your DoSomething with 'await Task.Yield();' to force it to return immediately, in case what's running before the first await is what's causing your UI issue.

Upvotes: 0

Jeff
Jeff

Reputation: 7674

How are you using await? This doesn't block the UI:

    private async Task DoSomething()
    {
        await Task.Delay(5000);
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        await DoSomething();
        MessageBox.Show("Finished");
    }

Note that I didn't have to write any verbose callback stuff. That's the point of async/await.

Upvotes: 4

Related Questions