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?
AsAsyncAction
is for turning tasks intoIAsyncAction
to 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.Run
is preferred in almost all cases.You also shouldn't create an async method to just use
Task.Run
inside 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 theThreadPool
it's better to let them useTask.Run
in their code.So basically just do this:
And let the caller call this method synchronously, or on a
ThreadPool
thread: