简体   繁体   中英

async await for virtual method

In our old synchronous application, we had the following in our base class:

public virtual bool ShouldSomethingHappen() => false;

So, the idea is that in the derived class, a call can be made to the DB to determine if something should happen.

So, when moving to awaited code, we first tried the following in the base class:

public virtual async Task<bool> ShouldSomethingHappen()
{
    await Task.Yield();
    return false;
}

This seemed to work fine when running the application, but it broke our integration tests (where we have many awaited calls)....we couldn't figure out why.

But, changing this to the following fixed the issue:

public virtual async Task<bool> ShouldSomethingHappen() => Task.FromResult(false);

So technically, what's the difference between the two approaches?

It could be that whatever happened in your integration tests after await Task.Yield() was not designed to work on a different thread. Task.Yield() causes method to continue running the rest of the method on another thread. When you use Task.FromResult you are returning already finished task. You are just returning completed task so it still happens on the same thread.

You can verify that by changing Task.FromResult(false) to Task.FromResult(false).ConfigureAwait(false) . await Task.Delay(n).ConfigureAwait(false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM