简体   繁体   中英

Async/Await action within Task.Run()

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 understand that Task.Run() is required since if we want to use await directly, then the calling method will need to be made Async and will affect the calling places.

Here is the sample code which has async await within Task.Run() . The full sample is provided here: Create pre-computed tasks .

Task.Run(async () => { await new WebClient().DownloadStringTaskAsync("");});

Alternatively this could have been done:

Task.Run(() => new WebClient().DownloadStringTaskAsync("").Result;);

Since both, Task.Run() and Await will queue the work and will be picked by the thread pool, could the async/await within the Task.Run() be a bit redundant?

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

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: HttpWebRequest does 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.

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.

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

Confirmed, wrapping await with Task.Run spawn 2 threads instead of one.

Task.Run(async () => { //thread 1
 await new WebClient().DownloadStringTaskAsync(""); //thread 2
});

Say you have two calls wrapped like this, it will spawn 2 x 2 = 4 threads.

It would be better to just call these with simple await instead. For example:

Task<byte[]> t1 = new WebClient().DownloadStringTaskAsync("");
Task<byte[]> t2 = new WebClient().DownloadStringTaskAsync("");
byte[] t1Result = await t1;
byte[] t2Result = await t2;

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