Aync/Await action within Task.Run()

前端 未结 4 522
南笙
南笙 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);
    });
    

提交回复
热议问题