简体   繁体   English

异步任务冻结UI

[英]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: 当我这样调用方法时,它会阻塞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 ? 那么,什么是点异步/的await时,你可以使用任务,因为他们在框架4和使用Task.Wait()代替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? 谁能给我一个基于任务的多线程示例,其中异步/等待可以提高程序的可读性和/或流程?

How are you using await ? 您如何使用await This doesn't block the UI: 这不会阻止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 . 这就是async / await

async methods begin their execution synchronously. async方法开始同步执行。 async is useful for composing asynchronous operations, but it does not magically make code run on another thread unless you tell it to. async对于组成异步操作很有用,但是除非您告知,否则它不会神奇地使代码在另一个线程上运行。

You can use Task.Run to schedule CPU-bound work to a threadpool thread. 您可以使用Task.Run将CPU绑定的工作调度到线程Task.Run线程。

See my async / await intro post or the async FAQ for more information. 有关更多信息,请参见我的async / await简介async常见问题解答

Without the actual code, it's hard to tell you what's going on, but you can start your DoSomething with 'await Task.Yield();' 没有实际的代码,很难告诉您发生了什么,但是您可以使用“ await Task.Yield();”开始DoSomething。 to force it to return immediately, in case what's running before the first await is what's causing your UI issue. 强制它立即返回,以防第一次等待前运行的是导致UI问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM