How to write an “awaitable” method?

后端 未结 6 1891
南笙
南笙 2020-12-07 13:20

I\'m finally looking into the async & await keywords, which I kind of "get", but all the examples I\'ve seen call async methods in the .Net framework, e.g. thi

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 13:28

    ... how I would write my own "awaitable" method.

    Returning a Task is not the only way. You have an option to create a custom awaiter (by implementing GetAwaiter and INotifyCompletion), here is a great read: "Await anything". Examples of .NET APIs returning custom awaiters: Task.Yield(), Dispatcher.InvokeAsync.

    I have some posts with custom awaiters here and here, e.g:

    // don't use this in production
    public static class SwitchContext
    {
        public static Awaiter Yield() { return new Awaiter(); }
    
        public struct Awaiter : System.Runtime.CompilerServices.INotifyCompletion
        {
            public Awaiter GetAwaiter() { return this; }
    
            public bool IsCompleted { get { return false; } }
    
            public void OnCompleted(Action continuation)
            {
                ThreadPool.QueueUserWorkItem((state) => ((Action)state)(), continuation);
            }
    
            public void GetResult() { }
        }
    }
    
    // ...
    
    await SwitchContext.Yield();
    

提交回复
热议问题