I have a bunch of work to do (either CPU-bound or IO-bound with no async interface to use) within an asynchronous method that returns a Task
. I'm wondering if it's OK to just do all the CPU-bound work within the asynchronous method like this:
async Task DoSomeStuff()
{
await SomethingAsync();
…
DoCpuBoundWork();
…
await SomethingElseAsync();
}
or should I use Task.Run
like this?
async Task DoSomeStuff()
{
await SomethingAsync();
…
await Task.Run(() => DoCpuBoundWork());
…
await SomethingElseAsync();
}
I know tasks aren't necessarily executed on another thread, so I'm wondering if the scheduler might make assumptions about tasks being non-blocking that'll make doing CPU-bound work outside of Task.Run
slow the application down. For example, if the scheduler decided to schedule the CPU-bound work to the app's UI thread, there could be a slow-down.