• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

为什么C#接口中不能声明async异步函数(转载)

Unable to declare Interface “ async Task<myObject> MyMethod(Object myObj); ”

 

问


 

I'm unable to declare

interface IMyInterface
{
   async Task<myObject> MyMethod(Object myObj);
}

The compiler tells me:

  • The modifier async isn't valid for this item
  • The async modifier can only be used for methods that have a body

Is this something that should be implemented, or does the nature of async & await prohibit this from ever occurring?

 

 

答1


 

Whether a method is implemented using async/await or not is an implementation detail. How the method should behave is a contract detail, which should be specified in the normal way.
Note that if you make the method return a Task or a Task<T>, it's more obvious that it's meant to be asynchronous, and will probably be hard to implement without being asynchronous.

From How to force async child overrides in C# 5.0

 

 

答2


 

Whether or not your implementation is async, has no relevance to your interface. In other words, the interface cannot specify that a given method must be implemented in an asynchronous way.
Just take async out of your interface and it will compile; however, there is no way to enforce asynchronous implementation just by specifying an interface.

 

 

原文链接

 

posted @ 2020-02-04 16:00  PowerCoder  阅读(2466)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3