I read this article with this example:
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;
}
}
It then describes how to call it depending on if you're using a UI based app or an ASP.NET app:
//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);
}
}
Why do you need to use Task.Run()
to execute PredictStockMarketAsync()
in the UI based app?
Wouldn't using await myService.PredictStockMarketAsync();
in a UI based app also not block the UI thread?