Whenever I have to start a parallel task I usually do this:
public async Task FindPerson(string personId)
{
await Task.Run(() =>
{
//Search the person and write to screen
});
}
However usually I see other coders using AsAsyncOperation:
public IAsyncAction FindPerson(string personId)
{
Task t = new Task(() =>
{
//Search the person and write to screen
});
t.Start();
return t.AsAsyncAction();
}
Does anyone have a clue on what benefits AsAsyncAction brings compared to using the brand new async/await?
AsAsyncActionis for turning tasks intoIAsyncActionto be passed to WinRT. If you don't use WinRT there's no reason to use this extension.You also shouldn't create a task and then start it.
Task.Runis preferred in almost all cases.You also shouldn't create an async method to just use
Task.Runinside it. The caller expects this method to be asynchronous but all it does is offload synchronous work to theThreadPool. If the caller needs that work on theThreadPoolit's better to let them useTask.Runin their code.So basically just do this:
And let the caller call this method synchronously, or on a
ThreadPoolthread: