Let's say I wanted to just quickly make the following method run asynchronously:
ResultType SynchronousCode(ParamType x)
{
return SomeLongRunningWebRequest(x);
}
What would be the difference in how the following two code samples are executed/scheduled?
async Task<ResultType> AsynchronousCode(ParamType x)
{
return await Task.Run(() => SomeLongRunningWebRequest(x));
}
Compared to:
async Task<ResultType> AsynchronousCode(ParamType x)
{
await Task.Yield();
return SomeLongRunningWebRequest(x);
}
I understand that the Task.Yield() call will ensure that the thread immediately returns to the caller, and that Task.Run() will definitely schedule the code to run somewhere on the ThreadPool, but do both of these methods effectively make the method async? Let's assume for this question that we are on the default SynchronizationContext.
While both options are bad, there is a difference (important in GUI applications): after Task.Yield
returns, the rest of the method will be dispatched back to original SynchronizationContext
. If you ran that from UI thread, your long running operation will be executed on UI thread, thus freezing it. So if your intention was to avoid UI blocking - Task.Yield
won't work. With Task.Run
that won't happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With