Search code examples
c#c#-4.0async-awaitiasyncoperation

AsAsyncAction VS Task.Run


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?


Solution

  • AsAsyncAction is for turning tasks into IAsyncAction 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 the ThreadPool. If the caller needs that work on the ThreadPool it's better to let them use Task.Run in their code.

    So basically just do this:

    public void FindPerson(string personId)
    {
        // Search the person and write to screen 
    }
    

    And let the caller call this method synchronously, or on a ThreadPool thread:

    Task.Run(() => FindPerson(personId));