Dev2345 Dev2345 - 2 months ago 21
C# Question

Task.Yield(); SyncAction(); vs Task.Run(()=>SyncAction());

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.

Evk Evk
Answer

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.