How to force async child overrides in C# 5.0

若如初见. 提交于 2019-11-28 18:33:47

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.

On the other hand, if there's an implementation (e.g. for test purposes) where the await expressions would never be incomplete, why would you want to force someone to write an async method with no await calls in anyway? You're expecting implementations to be IO-bound, but maybe there will be special cases where implementations want to use hard-coded data etc.

Basically you've got to handle this in the documentation for the method - if you can't trust implementers to read that, you've got no chance anyway :(

In addtion to Jon's answer, if you are following the Task-based Asynchronous Pattern then your method names should be suffixed with Async, which self documents that it is an asynchronous method.

If you're implementing an interface

public interface IFoo
{
    Task BarAsync();
}

it should be obvious that this should be implemented with the async keyword.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!