Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - Using a generic type as a return type of an async method

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 Task

public async T MyMethodAsync<T>() where T : Task
{
     // Irrelevant code here which returns a Task
}

Since we know at compile time that T is always a Task or a derived type, why won't this work?

Edit

The reason I'm asking is that a method may return a Task or a Task<T>. Let's say the method can return either and I don't want to duplicate code.

Of course this is all theoretical and isn't ment for production purposes.

Edit 2

Found a great article by Lucian Wischik: Why must async return Task

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Three problems:

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

  • The compiler needs to know whether it's building a state machine returning Task or Task<T> 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<T> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...