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

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

问题描述

我有这样一个方法:

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

当我调用该方法这样它会阻止用户界面:

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

Task t = DoSomething();

我必须做的其中之一,使其非阻塞:

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

// Or

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

那么,什么是异步/的await时,你可以使用,因为他们在框架4和使用任务 Task.Wait()代替<$ C点$ C>的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?

推荐答案

异步方法开始同步其执行。 异步是构成异步操作非常有用,但它不会神奇地让另一个线程code运行,除非你告诉它。

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.

请参阅我的 异步 / 的await 介绍后或的 异步常见问题解答更多信息。

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

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

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