I\'m finally looking into the async & await keywords, which I kind of "get", but all the examples I\'ve seen call async methods in the .Net framework, e.g. thi
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.