It's as simple as
Task.Run(() => ExpensiveTask());
To make it an awaitable method:
public Task ExpensiveTaskAsync()
{
return Task.Run(() => ExpensiveTask());
}
The important thing here is to return a task. The method doesn't even have to be marked async. (Just read a little bit further for it to come into the picture)
Now this can be called as
async public void DoStuff()
{
PrepareExpensiveTask();
await ExpensiveTaskAsync();
UseResultsOfExpensiveTask();
}
Note that here the method signature says async
, since the method may return control to the caller until ExpensiveTaskAsync()
returns. Also, expensive in this case means time-consuming, like a web request or similar. To send off heavy computation to another thread, it is usually better to use the "old" approaches, i.e. System.ComponentModel.BackgroundWorker
for GUI applications or System.Threading.Thread
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…