Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
499 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...