异步编程和虚函数

swi*_*ter 8 c# asynchronous windows-runtime windows-store-apps

如果我有一个界面,如:

using System.Threading.Tasks;

...

public interface IFoo
{
  Task doIt();

  Task<bool> doItAndReturnStuff();
}
Run Code Online (Sandbox Code Playgroud)

并且其中一个实现此接口的类恰好不需要异步方法,我如何才能正确覆盖这些函数?

换句话说,如何正确返回包装在Task对象中的"void"和"bool"?

例如:

public class FooHappensToNotNeedAsync : IFoo
{
  public override Task doIt()
  {
    // If I don't return anything here, I get
    // error that not all code paths return a value.
    // Can I just return null?
  }

  public override Task<bool> doItAndReturnStuff()
  {
    // If I want to return true, how to I do it?
    // This doesn't work:
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

注-我不能完全剥离任务的东西,因为一些实现此接口的类,其实非同步.

谢谢

Jon*_*eet 15

目前还不清楚你想要实现什么,但是一种方法(看起来最像"普通"代码)可能只是让它们成为异步方法:

public async Task DoIt()
{
    // No-op
}

public async Task<bool> DoItAndReturnStuff()
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

没有任何await表达式,该方法无论如何都将同步完成.你会得到一个关于每个方法的警告,但是你可以使用a来禁用这段代码#pragma.

或者 - 我想更简单地就不要求#pragma禁用警告 - 将使用Task.FromResult:

public Task DoIt()
{
    // Returns a Task<bool>, but that's okay - it's still a Task
    return Task.FromResult(true);
}

public Task<bool> DoItAndReturnStuff()
{
    return Task.FromResult(true);
}
Run Code Online (Sandbox Code Playgroud)