Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If it's possible to write our own awaitables, then why can async methods only return Task<T>, Task and void?

I'm looking at the MSDN documentation and it says

Async methods have three possible return types: Task<TResult>, Task, and void.

https://msdn.microsoft.com/en-us/library/mt674893.aspx

However, I remember reading somewhere else that it's possible to write to await custom awaiters. How can I reconcile these 2 facts?

like image 920
user7127000 Avatar asked Mar 10 '23 05:03

user7127000


1 Answers

await supports any kind of "awaitable", which are object instances that follow a certain pattern (GetAwaiter, etc).

async generates a state machine which only knows how to create Task/Task<T> awaitables (or return void).

So, you can create your own custom awaitable object and return that, but you have to do it explicitly. You can't use async to do it.

The compiler team is currently looking at adding ValueTask support to async. This would allow you to use "async method builders" that would follow a pattern. Then you'd be able to use async as well as await to operate on any kind of "tasklike" type. Unfortunately, it would still not allow async methods to return interface types, though - changes in other parts of the language are necessary for that.

like image 98
Stephen Cleary Avatar answered Mar 13 '23 05:03

Stephen Cleary