相关疑难解决方法(0)

无法声明接口"async Task <myObject> MyMethod(Object myObj);"

我无法申报

interface IMyInterface
{
   async Task<myObject> MyMethod(Object myObj);
}
Run Code Online (Sandbox Code Playgroud)

编译器告诉我:

  • 修饰符异步对此项无效
  • async修饰符只能用于具有正文的方法

这是应该实现的东西,还是async&await的性质是否禁止这种情况发生?

c# compiler-construction interface async-await asp.net-4.5

50
推荐指数
3
解决办法
3万
查看次数

在基类上使用虚拟异步方法是否可以?

我正在使用一些代码,我有2个类,逻辑和代码非常相似.我protected async void LoadDataAsync()在这两个课上都有方法.
目前我正在重构它并考虑将共享逻辑移动到基类.
是否可以virtual async在基类上使用方法并在派生类上覆盖它?
它有什么问题吗?
我的代码看起来像这样:

public class Base
{
   protected virtual async void LoadDataAsync() {}
}

public class Derived : Base
{
   protected override async void LoadDataAsync()
   {
       // awaiting something
   }
}
Run Code Online (Sandbox Code Playgroud)

已经提出类似(但不相同)的问题.

c# asynchronous async-await c#-5.0

43
推荐指数
2
解决办法
2万
查看次数

当我在接口方法调用上忘记`await`时没有警告

考虑:

using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        C c = new C();
        c.FooAsync(); // warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
        ((I)c).FooAsync(); // No warning
    }
}

class C : I
{
    public async Task FooAsync()
    {
    }
}

interface I
{
    Task FooAsync();
}
Run Code Online (Sandbox Code Playgroud)

如果我直接在c对象上调用async方法,我会收到编译器警告.这里可能有一个错误,所以我很高兴发出警告.

但是,如果我在接口方法上进行相同的调用,则不会收到警告.在这段代码中让一个错误过去很容易.

我如何确保不犯这个错误?我可以申请保护自己的模式吗?

c# async-await

23
推荐指数
1
解决办法
1296
查看次数