Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...