When correctly use Task.Run and when just async-await
When correctly use Task.Run and when just async-await
回答
Note the guidelines for performing work on a UI thread, collected on my blog:
- Don't block the UI thread for more than 50ms at a time.
- You can schedule ~100 continuations on the UI thread per second; 1000 is too much.
There are two techniques you should use:
1) Use ConfigureAwait(false)
when you can.
E.g., await MyAsync().ConfigureAwait(false);
instead of await MyAsync();
.
ConfigureAwait(false)
tells the await
that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async
method (after the ConfigureAwait
), you cannot do anything that assumes you're in the current context (e.g., update UI elements).
For more information, see my MSDN article Best Practices in Asynchronous Programming.
2) Use Task.Run
to call CPU-bound methods.
You should use Task.Run
, but not within any code you want to be reusable (i.e., library code). So you use Task.Run
to call the method, not as part of the implementation of the method.
So purely CPU-bound work would look like this:
// Documentation: This method is CPU-bound.
void DoWork();
Which you would call using Task.Run
:
await Task.Run(() => DoWork());
Methods that are a mixture of CPU-bound and I/O-bound should have an Async
signature with documentation pointing out their CPU-bound nature:
// Documentation: This method is CPU-bound.
Task DoWorkAsync();
Which you would also call using Task.Run
(since it is partially CPU-bound):
await Task.Run(() => DoWorkAsync());
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-07-05 The need for legislative reform on secrecy orders
2021-07-05 Can a foreign key be NULL and/or duplicate?
2019-07-05 The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
2017-07-05 Create the Data Access Layer
2015-07-05 Leap Years
2015-07-05 Find the capitals
2015-07-05 Area of a Circle