【发布时间】:2021-12-02 13:04:08
【问题描述】:
我通过这个例子阅读了这个article:
class MyService
{
/// <summary>
/// This method is CPU-bound!
/// </summary>
public async Task<int> PredictStockMarketAsync()
{
// Do some I/O first.
await Task.Delay(1000);
// Tons of work to do in here!
for (int i = 0; i != 10000000; ++i)
;
// Possibly some more I/O here.
await Task.Delay(1000);
// More work.
for (int i = 0; i != 10000000; ++i)
;
return 42;
}
}
然后描述如何根据您使用的是基于 UI 的应用程序还是 ASP.NET 应用程序来调用它:
//UI based app:
private async void MyButton_Click(object sender, EventArgs e)
{
await Task.Run(() => myService.PredictStockMarketAsync());
}
//ASP.NET:
public class StockMarketController: Controller
{
public async Task<ActionResult> IndexAsync()
{
var result = await myService.PredictStockMarketAsync();
return View(result);
}
}
为什么需要在基于 UI 的应用中使用Task.Run() 来执行PredictStockMarketAsync()?
在基于 UI 的应用程序中使用 await myService.PredictStockMarketAsync(); 不会也不会阻塞 UI 线程吗?
【问题讨论】:
-
因为
await在 WinForms/WPF 中的 UI thrad 上意味着“当您需要实际运行代码时请回到我的线程”... -
@MarcGravell 抱歉,我的问题中的代码有误,我现在已更新(仅最后两句话)。
-
FWIW,博客的作者在这里相当活跃 - 我不能召唤他们,虽然 :) 还值得注意的是,那里的文章现在已经 8 年了,也就是
await等是新的并且处于起步阶段(C# 5 于 2012 年 8 月发布);我希望我们对.ConfigureAwait(false)之类的集体知识在那时还低一些 -
@MarcGravell Blazor(在某种意义上是 asp.net 核心的一部分)确实有同步上下文。
标签: c# asynchronous async-await task-parallel-library ui-thread