await 可以作用于任何提供GetAwaiter方法的类
await
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| await FuncAsync();
async Task FuncAsync() { await Task.Delay(1000); }
var myDelay = new MyDelay(2); await myDelay;
class MyDelay { int second; public MyDelay(int second) { this.second = second; } public TaskAwaiter GetAwaiter() { return Task.Delay(TimeSpan.FromSeconds(second)).GetAwaiter(); } }
var myDelay = new MyDelay(2); await myDelay;
class MyDelay { public int second; public MyDelay(int second) { this.second = second; } } static class MyExtensions() { public static TaskAwaiter GetAwaiter(this MyDelay md) { return Task.Delay(TimeSpan.FromSeconds(md.second)).GetAwaiter(); } }
await TimeSpan.FromSeconds(2);
static class MyExtensions() { public static TaskAwaiter GetAwaiter(this MyDelay md) { return Task.Delay(TimeSpan.FromSeconds(md.second)).GetAwaiter(); } public static TaskAwaiter GetAwaiter(this TimeSpan ts) =>Task.Delay(ts).GetAwaiter(); }
await 2;
static class MyExtensions() { public static TaskAwaiter GetAwaiter(this MyDelay md) { return Task.Delay(TimeSpan.FromSeconds(md.second)).GetAwaiter(); } public static TaskAwaiter GetAwaiter(this TimeSpan ts) =>Task.Delay(ts).GetAwaiter(); public static TaskAwaiter GetAwaiter(this int second) =>Task.Delay(TimeSpan.FromSeconds(second)).GetAwaiter(); }
|