I'd like to know if the following use of async-await is safe given the apparent mix of asynchronous and synchronous code.
You have a derived class which overrides a virtual method and adds the async keyword to the method signature to declare it will do something asynchronous.
Note how in this exemple Foo calls Bar, and Bar in this case is derived and asynchronous, yet Foo does not await the call. It couldn't if it wanted to, on the base class the signature for Bar is synchronous.
public class BaseClass
{
public virtual void Foo()
{
Bar(); // note: there is no await on this call, yet Bar is async in derived class
}
protected virtual void Bar()
{
Console.WriteLine("Base.Bar");
}
}
// Derived class has implementation for Bar() which is asynchronous
// is that a problem? The compiler builds this, should we be worried about async and sync being mixed?
//
public class DerivedClass : BaseClass
{
protected override async void Bar()
{
Console.WriteLine("Derived.Bar");
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
var derived = new DerivedClass();
derived.Foo(); // note: there is no await on this call, yet Foo becomes async when it calls Bar which is async.
}
}
The reason I'm asking is that in Xamarin on Android it's recommended to override OnStart and add the async keyword when you want to do asynchronous code when an activity starts. Yet the method on the base Activity class is not async.