Using a generic type as a return type of an async method

后端 未结 2 1846
清歌不尽
清歌不尽 2020-12-17 20:35

A previous question made me wonder why the following method would raise a compile time error:

The return type of an async method must be void, Task or

2条回答
  •  一生所求
    2020-12-17 20:57

    I cannot think of a valid definition of MyMethodAsync that would allow it to return a generic T derived from Task without knowing at compile time what that type is or taking a parameter of some kind.

    If you are really returning a Task or Task then you can update your signature to reflect that fact and avoid the problem.

    If you honestly need some type derived from Task then you will need to rewrite your logic to instead return Task or Task and wrap around that other type. Assuming that is unacceptable you will need to drop the async and handle the state machine yourself.

提交回复
热议问题