覆盖方法并添加async关键字是否安全

时间:2018-04-17 23:37:05

标签: c# asynchronous xamarin xamarin.android async-await

我想知道,鉴于异步和同步代码的明显混合,以下使用async-await是否安全。

您有一个派生类,它覆盖了一个虚方法,并将async关键字添加到方法签名中,以声明它将执行异步操作。

注意在这个例子中Foo如何调用Bar,在这种情况下Bar是派生和异步的,但Foo不等待调用。它不能,如果它想要,在基类上Bar的签名是同步的。

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.
    }
}

我问的原因是,在Android上的Xamarin中,建议在活动开始时想要执行异步代码时重写OnStart并添加async关键字。然而,基本Activity类的方法不是异步的。

0 个答案:

没有答案