简体   繁体   中英

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?

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));

if you look at the MSDN page you will see that for IAsyncAction

  • .NET Framework Supported in: 4.6, 4.5
  • .NET for Windows Phone apps: Supported in: Windows Phone Silverlight 8

if you compare this to Task you will see

  • Universal Windows Platform: Available since 4.5
  • .NET Framework: Available since 4.0
  • Portable Class Library Supported in: portable .NET platforms
  • Silverlight: Available since 5.0
  • Windows Phone Silverlight Available since 8.0
  • Windows Phone Available since 8.1

this instantly tells you that IAsyncAction was created specifically for WinRT, which was MS's first real attempt at an Mobile App framework, because the full .net framework was too powerful to be safe on mobile devices they created a parallel cut down framework that would make it much harder to write malicious software that could damage a device

so if you are using WinRT then returning an IAsyncAction would be preferred anywhere else task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM