I have a virtual method that sometimes contain await calls and sometimes doesn't. The IDE does give me warning, what is the proper way of handling this ?
In my base class:
protected virtual async Task GoNext ()
From the base class it get called via await.
Then in my sub-classes i override this method but there are times that it does include a await and times that it doesn't.
The async
keyword is not actually part of the inherited method signature, but more of a signal to the compiler that it needs to compile and rewrite the method according to the pattern for async methods.
As such, you can leave out the async
keyword on inherited methods if the inherited method does not use the await
keyword.
Note that you will still have to return a Task
or Task<T>
, that part is part of the inherited method signature.
So this will give you a warning:
class Base
{
public virtual async Task<int> Method()
{
await Task.Delay(10);
return 42;
}
}
class Derived : Base
{
// next line produces warning
public override async Task<int> Method()
{
return 42;
}
}
The warning is this:
Warning: CS1998 This async method lacks 'await' operators and will run synchronously. Consider using the
await
operator to await non-blocking API calls, orawait Task.Run(...)
to do CPU-bound work on a background thread.
This, however, will not produce a warning:
class Derived : Base
{
public override Task<int> Method()
{
return Task.FromResult(42);
}
}
Note that I changed the return
statement in that last method because part of the "magic" that the async
keyword brings is to automatically wrap the return value inside a Task<T>
. If you have other ways of obtaining a Task<T>
, obviously you do not need to wrap the result like I did above.
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