Sometimes we we want to decorate an intrinsically synchronously method with
async
, and we receive this error.
This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
That error message tells us one way to solve the problem, but its recommendation is to open up another thread, which isn't necessarily what we want to do.
public async Task<MyObject> GetEntity()
{
// run on a new thread
return await Task.Run(() => new MyObject());
}
Instead, we can use
Task.Yield()
, which yields control to the calling method.
Here is a Fiddle
and a small snippet.
public async Task<MyObject> GetEntity()
{
// return control to the caller
await Task.Yield();
// continue later on the same thread
return new MyObject();
}
Task.Yield()
has a similar effect to
Task.Delay(0)
and
Task.FromResult(0)
.