地铁c#中的虚拟异步方法

ofe*_*fer 1 c# asynchronous task-parallel-library async-await windows-runtime

我想定义一个在基类中不是异步的虚方法,但它在派生类中是异步的,调用者使用委托调用它(实际上它是由屏幕上的按钮激活的ICommand)我该怎么做.

public class BaseClass
{
    BIONESSBindingCommand mLogoffCommand;

    public ICommand LogoffCommand
    {
        get
        {
            if (mLogoffCommand == null)
            {
                mLogoffCommand = new BIONESSBindingCommand(
                    Param => Logoff(), //Command DoWork
                    Param => true); //Always can execute
            }

            return mLogoffCommand;
        }
    }

    public virtual Task Logoff()
    {
        DoLogoff();
        return null; //???
    }
}

public class DerivedClass : BaseClass
{
    public override async Task Logoff()
    {
        await SomeWoAsyncWork();
        base.Logoff(); //Has warninngs
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ary 5

打电话Task.FromResult来完成Task.此外,await它在派生类中(这将启用错误传播).

public class BaseClass
{
  public virtual Task Logoff()
  {
    DoLogoff();
    return Task.FromResult(false);
  }
}

public class DerivedClass : BaseClass
{
  public override async Task Logoff()
  {
    await SomeWoAsyncWork();
    await base.Logoff();
  }
}
Run Code Online (Sandbox Code Playgroud)