自定义一个awaiter 代码来自网络
using System; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; class TestAwaiter<T> : INotifyCompletion { private T result; private Action continuation; // INotifyCompletion Implement public void OnCompleted(Action continuation) { this.continuation = continuation; } // Compiler Call Methods public bool IsCompleted { get; private set; } public T GetResult() { return result; } public TestAwaiter<T> GetAwaiter() { return this; } // Self Call Methods public void SetResult(T ret) { result = ret; if (continuation != null) { continuation(); } } } class Test { public static void Main(string[] args) { Task.Run(new Action(task1)); Console.ReadLine(); } private async static void task1() { Console.WriteLine("Begin await:"); int ret = await testAwaiter(); Console.WriteLine("Await Task Result:" + ret); } private static TestAwaiter<int> testAwaiter() { TestAwaiter<int> awaiter = new TestAwaiter<int>(); ThreadPool.QueueUserWorkItem(_ => { Thread.Sleep(3000); awaiter.SetResult(100); }); return awaiter; } }