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

后端 未结 2 1849
清歌不尽
清歌不尽 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:59

    Three problems:

    • Just because T is "Task or a derived type" doesn't mean that it's Task or Task. What would you expect if I called MyMethodAsync where MyCustomTask derives from Task?

    • The compiler needs to know whether it's building a state machine returning Task or Task when it compiles the method - it uses different helper classes in the different cases

    • If an async method has a return type of Task, any return statements can't specify a value; if it has a return type of Task any return statements must specify a value which is implicitly convertible to T. How can that work within MyMethodAsync? It's a bit like saying "my method is either void or returns a T - you can decide when you call it".

    It's not clear what you're trying to achieve here, but basically this isn't going to work.

提交回复
热议问题