异步任务正在冻结 UI [英] async Task is freezing the UI

查看:23
本文介绍了异步任务正在冻结 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的方法:

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

当我像这样调用方法时,它会阻塞 UI:

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());

那么,当您可以像在框架 4 中那样使用任务并使用 Task.Wait() 代替 await 时,async/await 的意义何在?

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?

我理解你所有的答案——但没有一个真正解决我的最后一段.谁能给我一个基于任务的多线程示例,其中 async/await 提高了程序的可读性和/或流程?

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?

推荐答案

async 方法开始同步执行.async 对于组合异步操作很有用,但它不会神奇地让代码在另一个线程上运行,除非你告诉它.

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.

您可以使用 Task.Run 将 CPU 密集型工作调度到线程池线程.

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

见我的async/await 介绍帖子async 常见问题解答了解更多信息.

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

这篇关于异步任务正在冻结 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆