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