Aync/Await action within Task.Run()

前端 未结 4 411
南笙
南笙 2020-12-09 10:21

Task.Run(()=>{}) puts the action delegate into the queue and returns the task . Is there any benefit of having async/await within the Task.Run() ? I underst

相关标签:
4条回答
  • 2020-12-09 11:00

    Is there any benefit of having async/await within the Task.Run() ?

    Yes. Task.Run runs some action on a thread-pool thread. If such action does some IO work and asynchronously waits for the IO operation to complete via await, then this thread-pool thread can be used by the system for other work while the IO operation is still running.

    Example:

    Task.Run( async () =>
    {
        DoSomeCPUIntensiveWork();
    
        // While asynchronously waiting for this to complete, 
        // the thread is given back to the thread-pool
        var io_result = await DoSomeIOOperation(); 
    
        DoSomeOtherCPUIntensiveWork(io_result);
    });
    
    0 讨论(0)
  • 2020-12-09 11:16

    Is there any benefit of having async/await within the Task.Run()

    You also could ask the opposite question: Why would you wrap an async/await code in Task.Run?!

    An async method returns to the caller as soon as the first await is hit (that operates on a non-completed task). So if that first execution "streak" of an async method takes a long time Task.Run will alter behavior: It will cause the method to immediately return and execute that first "streak" on the thread-pool.

    This is useful in UI scenarios because that way you can make 100% sure that you are not blocking the UI. Example: HttpWebRequestdoes DNS resolution synchronously even when you use one of the async methods (this is basically a library bug/design error). This can pause the UI thread. So you can use Task.Run to be 100% sure that the UI is never blocked for longer than a few microseconds.

    So back to the original question: Why await inside a Task.Run body? For the same reason you normally await: To unblock the thread.

    0 讨论(0)
  • 2020-12-09 11:20

    In the example that you linked the main thread is being blocked until the asynchronous operation is done. It's being blocked by calling Wait() (which by the way is generally a bad idea).

    Let's have a look at the return from the DownloadStringAsync in the linked sample:

    return Task.Run(async () =>
    {
        content = await new WebClient().DownloadStringTaskAsync(address);
        cachedDownloads.TryAdd(address, content);
        return content;
    });
    

    Why would you wrap this in a Task? Think about your options for a second. If you don't want to wrap this in a Task, how would you make sure the method returns a Task<string> and still have it work? You'd mark the method as async of course! However, if you mark your method as async and you call Wait on it, you'll most likely end up with a deadlock, since the main thread is waiting for the work to finish, and your blocking the main thread so it can't let you know it's done.

    When marking a method as async, the state machine will run on the calling thread, in your example however, the state machine runs on a separate thread, meaning there is little to no work being done on the main thread.

    0 讨论(0)
  • 2020-12-09 11:22

    Calling Async from Non-Async Methods

    We do some stuff like that when we are trying to call an async method inside of a non-async method. Especially if the async method is a known quantity. We use more of a TaskFactory though ... fits a pattern, makes it easier to debug, makes sure everyone takes the same approach (and -- gives us one throat to choke if async-->sync starts acting buggy).

    So, Your Example

    Imagine, in your example, that you have a non-async function. And, within that function, you need to call await webClient.DoSomethingAsync(). You can't call await inside of a function that's not async -- the compiler won't let you.

    Option 1: Zombie Infestation

    Your first option is to crawl all the way back up your call stack, marking every da*n method along the way as async and adding awaits everywhere. Everywhere. Like, everywhere. Then -- since all those methods are now async, you need to make the methods that reference them all async.

    This, btw, is probably the approach many of the SO enthusiasts are going to advocate. Because, "blocking a thread is a bad idea."

    So. Yeah. This "let async be async" approach means your little library routine to get a json object just reached out and touched 80% of the code. Who's going to call the CTO and let him know?

    Option 2: Just Go with the One Zombie

    OR, you can encapsulate your async inside of some function like yours...

    return Task.Run(async () => {
         content = await new WebClient().DoSomethingAsync();
         cachedDownloads.TryAdd(address, content);
         return content;
    });
    

    Presto... the zombie infestation has been contained to a single section of code. I'll leave it to the bit-mechanics to argue over how/why that gets executed at the CPU-level. I don't really care. I care that nobody has to explain to the CTO why the entire library should now be 100% async (or something like that).

    0 讨论(0)
提交回复
热议问题