Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 840
Dev2345 Avatar asked Sep 12 '16 19:09

Dev2345


1 Answers

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.

like image 71
Evk Avatar answered Sep 16 '22 18:09

Evk