-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch11.cs
398 lines (326 loc) · 8.35 KB
/
ch11.cs
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Nito.AsyncEx;
class ch11r01
{
interface IMyAsyncInterface
{
Task<int> CountBytesAsync(HttpClient client, string url);
}
class MyAsyncClass : IMyAsyncInterface
{
public async Task<int> CountBytesAsync(HttpClient client, string url)
{
var bytes = await client.GetByteArrayAsync(url);
return bytes.Length;
}
}
async Task UseMyInterfaceAsync(HttpClient client, IMyAsyncInterface service)
{
var result = await service.CountBytesAsync(client, "http://www.example.com");
Trace.WriteLine(result);
}
class MyAsyncClassStub : IMyAsyncInterface
{
public Task<int> CountBytesAsync(HttpClient client, string url)
{
return Task.FromResult(13);
}
}
}
class ch11r02A
{
class MyAsyncClass
{
public Task InitializeAsync() => Task.CompletedTask;
}
async Task Test()
{
var instance = new MyAsyncClass();
await instance.InitializeAsync();
}
}
class ch11r02B
{
class MyAsyncClass
{
private MyAsyncClass()
{
}
private async Task<MyAsyncClass> InitializeAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
return this;
}
public static Task<MyAsyncClass> CreateAsync()
{
var result = new MyAsyncClass();
return result.InitializeAsync();
}
}
async Task Test()
{
MyAsyncClass instance = await MyAsyncClass.CreateAsync();
}
}
class ch11r02C
{
class MyAsyncClass
{
public MyAsyncClass()
{
InitializeAsync();
}
// BAD CODE!!
private async void InitializeAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
}
class ch11r03A
{
interface IMyFundamentalType { }
interface IMyComposedType { }
/// <summary>
/// Marks a type as requiring asynchronous initialization
/// and provides the result of that initialization.
/// </summary>
public interface IAsyncInitialization
{
/// <summary>
/// The result of the asynchronous initialization of this instance.
/// </summary>
Task Initialization { get; }
}
class MyFundamentalType : IMyFundamentalType, IAsyncInitialization
{
public MyFundamentalType()
{
Initialization = InitializeAsync();
}
public Task Initialization { get; private set; }
private async Task InitializeAsync()
{
// Asynchronously initialize this instance.
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
async Task Test1()
{
IMyFundamentalType instance = new MyFundamentalType(); // UltimateDIFactory.Create<IMyFundamentalType>();
var instanceAsyncInit = instance as IAsyncInitialization;
if (instanceAsyncInit != null)
await instanceAsyncInit.Initialization;
}
class MyComposedType : IMyComposedType, IAsyncInitialization
{
private readonly IMyFundamentalType _fundamental;
public MyComposedType(IMyFundamentalType fundamental)
{
_fundamental = fundamental;
Initialization = InitializeAsync();
}
public Task Initialization { get; private set; }
private async Task InitializeAsync()
{
// Asynchronously wait for the fundamental instance to initialize,
// if necessary.
var fundamentalAsyncInit = _fundamental as IAsyncInitialization;
if (fundamentalAsyncInit != null)
await fundamentalAsyncInit.Initialization;
// Do our own initialization (synchronous or asynchronous).
// ...
}
}
public static class AsyncInitialization
{
public static Task WhenAllInitializedAsync(params object[] instances)
{
return Task.WhenAll(instances
.OfType<IAsyncInitialization>()
.Select(x => x.Initialization));
}
}
class MyComposedType2 : IMyComposedType, IAsyncInitialization
{
private readonly IMyFundamentalType _fundamental, _anotherType, _yetAnother;
public MyComposedType2(IMyFundamentalType fundamental)
{
_fundamental = fundamental;
Initialization = InitializeAsync();
}
public Task Initialization { get; private set; }
private async Task InitializeAsync()
{
// Asynchronously wait for all 3 instances to initialize, if necessary.
await AsyncInitialization.WhenAllInitializedAsync(_fundamental,
_anotherType, _yetAnother);
// Do our own initialization (synchronous or asynchronous).
// ...
}
}
}
class ch11r04A
{
// As an asynchronous method.
public async Task<int> GetDataAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
return 13;
}
}
class ch11r04B
{
// As a Task-returning property.
// This API design is questionable.
public Task<int> Data
{
get { return GetDataAsync(); }
}
private async Task<int> GetDataAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
return 13;
}
}
class ch11r04C
{
// As a cached value.
public AsyncLazy<int> Data
{
get { return _data; }
}
private readonly AsyncLazy<int> _data =
new AsyncLazy<int>(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1));
return 13;
});
async Task Test()
{
var instance = new ch11r04C();
int value = await instance.Data;
}
}
class ch11r04D
{
private async Task<int> GetDataAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
return 13;
}
public int Data
{
// BAD CODE!!
get { return GetDataAsync().Result; }
}
}
class ch11r05
{
public class MyEventArgs : EventArgs, IDeferralSource
{
private readonly DeferralManager _deferrals = new DeferralManager();
// ... // Your own constructors and properties.
public IDisposable GetDeferral()
{
return _deferrals.DeferralSource.GetDeferral();
}
internal Task WaitForDeferralsAsync()
{
return _deferrals.WaitForDeferralsAsync();
}
}
public event EventHandler<MyEventArgs> MyEvent;
private async Task RaiseMyEventAsync()
{
EventHandler<MyEventArgs> handler = MyEvent;
if (handler == null)
return;
var args = new MyEventArgs();
handler(this, args);
await args.WaitForDeferralsAsync();
}
async void AsyncHandler(object sender, MyEventArgs args)
{
using IDisposable deferral = args.GetDeferral();
await Task.Delay(TimeSpan.FromSeconds(2));
}
}
class ch11r06A
{
class MyClass : IDisposable
{
private readonly CancellationTokenSource _disposeCts =
new CancellationTokenSource();
public async Task<int> CalculateValueAsync()
{
await Task.Delay(TimeSpan.FromSeconds(2), _disposeCts.Token);
return 13;
}
public void Dispose()
{
_disposeCts.Cancel();
}
}
}
class ch11r06B
{
class MyClass : IDisposable
{
private readonly CancellationTokenSource _disposeCts =
new CancellationTokenSource();
public async Task<int> CalculateValueAsync(CancellationToken cancellationToken)
{
using CancellationTokenSource combinedCts = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken, _disposeCts.Token);
await Task.Delay(TimeSpan.FromSeconds(2), combinedCts.Token);
return 13;
}
public void Dispose()
{
_disposeCts.Cancel();
}
}
async Task UseMyClassAsync()
{
Task<int> task;
using (var resource = new MyClass())
{
task = resource.CalculateValueAsync(default);
}
// Throws OperationCanceledException.
var result = await task;
}
}
class ch11r06C
{
class MyClass : IAsyncDisposable
{
public async ValueTask DisposeAsync()
{
await Task.Delay(TimeSpan.FromSeconds(2));
}
}
async Task Test()
{
await using (var myClass = new MyClass())
{
// ...
} // DisposeAsync is invoked (and awaited) here
}
async Task Test2()
{
var myClass = new MyClass();
await using (myClass.ConfigureAwait(false))
{
// ...
} // DisposeAsync is invoked (and awaited) here with ConfigureAwait(false)
}
}