首页 > Windows开发 > 详细

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

时间:2020-02-04 16:19:36      阅读:396      评论:0      收藏:0      [点我收藏+]

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.

 

 

原文链接

 

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

原文:https://www.cnblogs.com/OpenCoder/p/12259777.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!