Can I await something if there's no GetAwaiter method?

前端 未结 2 1741
忘了有多久
忘了有多久 2020-12-09 06:15

I saw some articles about designing a custom awaitable type:

http://books.google.com.br/books?id=1On1glEbTfIC&pg=PA83&lpg=PA83&dq=create+a+custom+awaitab

相关标签:
2条回答
  • 2020-12-09 06:55

    You can supply your own implementation of GetAwaiter via an extension method if one does not exist.

    http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115642.aspx

    0 讨论(0)
  • 2020-12-09 07:17

    First of all, no.

    You can't await something that doesn't have a GetAwaiter method that returns something that has GetResult, OnCompleted, IsCompleted and implements INotifyCompletion.

    So, how are you able to await an IObservable<T>?

    The compiler, on top of instance methods, also accepts GetAwaiter extensions methods. In this case Reactive Extensions's Observable provides that extension:

    public static AsyncSubject<TSource> GetAwaiter<TSource>(this IObservable<TSource> source);
    

    For example, this is how we can make strings awaitable (which compiles but obviously won't actually work):

    public static Awaiter GetAwaiter(this string s)
    {
        throw new NotImplementedException();
    }
    public abstract class Awaiter : INotifyCompletion
    {
        public abstract bool IsCompleted { get; }
        public abstract void GetResult();
        public abstract void OnCompleted(Action continuation);
    }
    

    await "bar";
    
    0 讨论(0)
提交回复
热议问题