-
Notifications
You must be signed in to change notification settings - Fork 736
/
AsyncGuidance.md
1452 lines (1119 loc) · 50.7 KB
/
AsyncGuidance.md
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Table of contents
- [Asynchronous Programming](#asynchronous-programming)
- [Asynchrony is viral](#asynchrony-is-viral)
- [Async void](#async-void)
- [Prefer Task.FromResult over Task.Run for pre-computed or trivially computed data](#prefer-taskfromresult-over-taskrun-for-pre-computed-or-trivially-computed-data)
- [Avoid using Task.Run for long running work that blocks the thread](#avoid-using-taskrun-for-long-running-work-that-blocks-the-thread)
- [Avoid using Task.Result and Task.Wait](#avoid-using-taskresult-and-taskwait)
- [Prefer await over ContinueWith](#prefer-await-over-continuewith)
- [Always create TaskCompletionSource\<T\> with TaskCreationOptions.RunContinuationsAsynchronously](#always-create-taskcompletionsourcet-with-taskcreationoptionsruncontinuationsasynchronously)
- [Always dispose CancellationTokenSource(s) used for timeouts](#always-dispose-cancellationtokensources-used-for-timeouts)
- [Always flow CancellationToken(s) to APIs that take a CancellationToken](#always-flow-cancellationtokens-to-apis-that-take-a-cancellationtoken)
- [Cancelling uncancellable operations](#cancelling-uncancellable-operations)
- [Always call FlushAsync on StreamWriter(s) or Stream(s) before calling Dispose](#always-call-flushasync-on-streamwriters-or-streams-before-calling-dispose)
- [Prefer async/await over directly returning Task](#prefer-asyncawait-over-directly-returning-task)
- [AsyncLocal\<T\>](#asynclocalt)
- [ConfigureAwait](#configureawait)
- [Scenarios](#scenarios)
- [Timer callbacks](#timer-callbacks)
- [Implicit async void delegates](#implicit-async-void-delegates)
- [ConcurrentDictionary.GetOrAdd](#concurrentdictionarygetoradd)
- [Constructors](#constructors)
- [WindowsIdentity.RunImpersonated](#windowsidentityrunimpersonated)
# Asynchronous Programming
Asynchronous programming has been around for several years on the .NET platform but has historically been very difficult to do well. Since the introduction of async/await
in C# 5 asynchronous programming has become mainstream. Modern frameworks (like ASP.NET Core) are fully asynchronous and it's very hard to avoid the async keyword when writing
web services. As a result, there's been lots of confusion on the best practices for async and how to use it properly. This section will try to lay out some guidance with examples of bad and good patterns of how to write asynchronous code.
## Asynchrony is viral
Once you go async, all of your callers **SHOULD** be async, since efforts to be async amount to nothing unless the entire callstack is async. In many cases, being partially async can be worse than being entirely synchronous. Therefore it is best to go all in, and make everything async at once.
❌ **BAD** This example uses the `Task.Result` and as a result blocks the current thread to wait for the result. This is an example of [sync over async](#avoid-using-taskresult-and-taskwait).
```C#
public int DoSomethingAsync()
{
var result = CallDependencyAsync().Result;
return result + 1;
}
```
:white_check_mark: **GOOD** This example uses the await keyword to get the result from `CallDependencyAsync`.
```C#
public async Task<int> DoSomethingAsync()
{
var result = await CallDependencyAsync();
return result + 1;
}
```
## Async void
Use of async void in ASP.NET Core applications is **ALWAYS** bad. Avoid it, never do it. Typically, it's used when developers are trying to implement fire and forget patterns triggered by a controller action. Async void methods will crash the process if an exception is thrown. We'll look at more of the patterns that cause developers to do this in ASP.NET Core applications but here's a simple example:
❌ **BAD** Async void methods can't be tracked and therefore unhandled exceptions can result in application crashes.
```C#
public class MyController : Controller
{
[HttpPost("/start")]
public IActionResult Post()
{
BackgroundOperationAsync();
return Accepted();
}
public async void BackgroundOperationAsync()
{
var result = await CallDependencyAsync();
DoSomething(result);
}
}
```
:white_check_mark: **GOOD** `Task`-returning methods are better since unhandled exceptions trigger the [`TaskScheduler.UnobservedTaskException`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskscheduler.unobservedtaskexception?view=netframework-4.7.2).
```C#
public class MyController : Controller
{
[HttpPost("/start")]
public IActionResult Post()
{
Task.Run(BackgroundOperationAsync);
return Accepted();
}
public async Task BackgroundOperationAsync()
{
var result = await CallDependencyAsync();
DoSomething(result);
}
}
```
## Prefer `Task.FromResult` over `Task.Run` for pre-computed or trivially computed data
For pre-computed results, there's no need to call `Task.Run`, that will end up queuing a work item to the thread pool that will immediately complete with the pre-computed value. Instead, use `Task.FromResult`, to create a task wrapping already computed data.
❌ **BAD** This example wastes a thread-pool thread to return a trivially computed value.
```C#
public class MyLibrary
{
public Task<int> AddAsync(int a, int b)
{
return Task.Run(() => a + b);
}
}
```
:white_check_mark: **GOOD** This example uses `Task.FromResult` to return the trivially computed value. It does not use any extra threads as a result.
```C#
public class MyLibrary
{
public Task<int> AddAsync(int a, int b)
{
return Task.FromResult(a + b);
}
}
```
:bulb:**NOTE: Using `Task.FromResult` will result in a `Task` allocation. Using `ValueTask<T>` can completely remove that allocation.**
:white_check_mark: **GOOD** This example uses a `ValueTask<int>` to return the trivially computed value. It does not use any extra threads as a result. It also does not allocate an object on the managed heap.
```C#
public class MyLibrary
{
public ValueTask<int> AddAsync(int a, int b)
{
return new ValueTask<int>(a + b);
}
}
```
## Avoid using Task.Run for long running work that blocks the thread
Long running work in this context refers to a thread that's running for the lifetime of the application doing background work (like processing queue items, or sleeping and waking up to process some data). `Task.Run` will queue a work item to the thread pool. The assumption is that that work will finish quickly (or quickly enough to allow reusing that thread within some reasonable timeframe). Stealing a thread-pool thread for long-running work is bad since it takes that thread away from other work that could be done (timer callbacks, task continuations etc). Instead, spawn a new thread manually to do long running blocking work.
:bulb: **NOTE: The thread pool grows if you block threads but it's bad practice to do so.**
:bulb: **NOTE:`Task.Factory.StartNew` has an option `TaskCreationOptions.LongRunning` that under the covers creates a new thread and returns a Task that represents the execution. Using this properly requires several non-obvious parameters to be passed in to get the right behavior on all platforms.**
:bulb: **NOTE: Don't use `TaskCreationOptions.LongRunning` with async code as this will create a new thread which will be destroyed after first `await`.**
❌ **BAD** This example steals a thread-pool thread forever, to execute queued work on a `BlockingCollection<T>`.
```C#
public class QueueProcessor
{
private readonly BlockingCollection<Message> _messageQueue = new BlockingCollection<Message>();
public void StartProcessing()
{
Task.Run(ProcessQueue);
}
public void Enqueue(Message message)
{
_messageQueue.Add(message);
}
private void ProcessQueue()
{
foreach (var item in _messageQueue.GetConsumingEnumerable())
{
ProcessItem(item);
}
}
private void ProcessItem(Message message) { }
}
```
:white_check_mark: **GOOD** This example uses a dedicated thread to process the message queue instead of a thread-pool thread.
```C#
public class QueueProcessor
{
private readonly BlockingCollection<Message> _messageQueue = new BlockingCollection<Message>();
public void StartProcessing()
{
var thread = new Thread(ProcessQueue)
{
// This is important as it allows the process to exit while this thread is running
IsBackground = true
};
thread.Start();
}
public void Enqueue(Message message)
{
_messageQueue.Add(message);
}
private void ProcessQueue()
{
foreach (var item in _messageQueue.GetConsumingEnumerable())
{
ProcessItem(item);
}
}
private void ProcessItem(Message message) { }
}
```
## Avoid using `Task.Result` and `Task.Wait`
There are very few ways to use `Task.Result` and `Task.Wait` correctly so the general advice is to completely avoid using them in your code.
### :warning: Sync over `async`
Using `Task.Result` or `Task.Wait` to block wait on an asynchronous operation to complete is *MUCH* worse than calling a truly synchronous API to block. This phenomenon is dubbed "Sync over async". Here is what happens at a very high level:
- An asynchronous operation is kicked off.
- The calling thread is blocked waiting for that operation to complete.
- When the asynchronous operation completes, it unblocks the code waiting on that operation. This takes place on another thread.
The result is that we need to use 2 threads instead of 1 to complete synchronous operations. This usually leads to [thread-pool starvation](https://blogs.msdn.microsoft.com/vancem/2018/10/16/diagnosing-net-core-threadpool-starvation-with-perfview-why-my-service-is-not-saturating-all-cores-or-seems-to-stall/) and results in service outages.
### :warning: Deadlocks
The `SynchronizationContext` is an abstraction that gives application models a chance to control where asynchronous continuations run. ASP.NET (non-core), WPF and Windows Forms each have an implementation that will result in a deadlock if Task.Wait or Task.Result is used on the main thread. This behavior has led to a bunch of "clever" code snippets that show the "right" way to block waiting for a Task. The truth is, there's no good way to block waiting for a Task to complete.
:bulb:**NOTE: ASP.NET Core does not have a `SynchronizationContext` and is not prone to the deadlock problem.**
❌ **BAD** The below are all examples that are, in one way or another, trying to avoid the deadlock situation but still succumb to "sync over async" problems.
```C#
public string DoOperationBlocking()
{
// Bad - Blocking the thread that enters.
// DoAsyncOperation will be scheduled on the default task scheduler, and remove the risk of deadlocking.
// In the case of an exception, this method will throw an AggregateException wrapping the original exception.
return Task.Run(() => DoAsyncOperation()).Result;
}
public string DoOperationBlocking2()
{
// Bad - Blocking the thread that enters.
// DoAsyncOperation will be scheduled on the default task scheduler, and remove the risk of deadlocking.
// In the case of an exception, this method will throw the exception without wrapping it in an AggregateException.
return Task.Run(() => DoAsyncOperation()).GetAwaiter().GetResult();
}
public string DoOperationBlocking3()
{
// Bad - Blocking the thread that enters, and blocking the threadpool thread inside.
// In the case of an exception, this method will throw an AggregateException containing another AggregateException, containing the original exception.
return Task.Run(() => DoAsyncOperation().Result).Result;
}
public string DoOperationBlocking4()
{
// Bad - Blocking the thread that enters, and blocking the threadpool thread inside.
return Task.Run(() => DoAsyncOperation().GetAwaiter().GetResult()).GetAwaiter().GetResult();
}
public string DoOperationBlocking5()
{
// Bad - Blocking the thread that enters.
// Bad - No effort has been made to prevent a present SynchonizationContext from becoming deadlocked.
// In the case of an exception, this method will throw an AggregateException wrapping the original exception.
return DoAsyncOperation().Result;
}
public string DoOperationBlocking6()
{
// Bad - Blocking the thread that enters.
// Bad - No effort has been made to prevent a present SynchonizationContext from becoming deadlocked.
return DoAsyncOperation().GetAwaiter().GetResult();
}
public string DoOperationBlocking7()
{
// Bad - Blocking the thread that enters.
// Bad - No effort has been made to prevent a present SynchonizationContext from becoming deadlocked.
var task = DoAsyncOperation();
task.Wait();
return task.GetAwaiter().GetResult();
}
```
## Prefer `await` over `ContinueWith`
`Task` existed before the async/await keywords were introduced and as such provided ways to execute continuations without relying on the language. Although these methods are still valid to use, we generally recommend that you prefer `async`/`await` to using `ContinueWith`. `ContinueWith` also does not capture the `SynchronizationContext` and as a result is actually semantically different to `async`/`await`.
❌ **BAD** The example uses `ContinueWith` instead of `async`
```C#
public Task<int> DoSomethingAsync()
{
return CallDependencyAsync().ContinueWith(task =>
{
return task.Result + 1;
});
}
```
:white_check_mark: **GOOD** This example uses the `await` keyword to get the result from `CallDependencyAsync`.
```C#
public async Task<int> DoSomethingAsync()
{
var result = await CallDependencyAsync();
return result + 1;
}
```
## Always create `TaskCompletionSource<T>` with `TaskCreationOptions.RunContinuationsAsynchronously`
`TaskCompletionSource<T>` is an important building block for libraries trying to adapt things that are not inherently awaitable to be awaitable via a `Task`. It is also commonly used to build higher-level operations (such as batching and other combinators) on top of existing asynchronous APIs. By default, `Task` continuations will run *inline* on the same thread that calls Try/Set(Result/Exception/Canceled). As a library author, this means having to understand that calling code can resume directly on your thread. This is extremely dangerous and can result in deadlocks, thread-pool starvation, corruption of state (if code runs unexpectedly) and more.
Always use `TaskCreationOptions.RunContinuationsAsynchronously` when creating the `TaskCompletionSource<T>`. This will dispatch the continuation onto the thread pool instead of executing it inline.
❌ **BAD** This example does not use `TaskCreationOptions.RunContinuationsAsynchronously` when creating the `TaskCompletionSource<T>`.
```C#
public Task<int> DoSomethingAsync()
{
var tcs = new TaskCompletionSource<int>();
var operation = new LegacyAsyncOperation();
operation.Completed += result =>
{
// Code awaiting on this task will resume on this thread!
tcs.SetResult(result);
};
return tcs.Task;
}
```
:white_check_mark: **GOOD** This example uses `TaskCreationOptions.RunContinuationsAsynchronously` when creating the `TaskCompletionSource<T>`.
```C#
public Task<int> DoSomethingAsync()
{
var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var operation = new LegacyAsyncOperation();
operation.Completed += result =>
{
// Code awaiting on this task will resume on a different thread-pool thread
tcs.SetResult(result);
};
return tcs.Task;
}
```
:bulb:**NOTE: There are 2 enums that look alike. [`TaskCreationOptions.RunContinuationsAsynchronously`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcreationoptions?view=netcore-2.0#System_Threading_Tasks_TaskCreationOptions_RunContinuationsAsynchronously) and [`TaskContinuationOptions.RunContinuationsAsynchronously`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcontinuationoptions?view=netcore-2.0). Be careful not to confuse their usage.**
## Always dispose `CancellationTokenSource`(s) used for timeouts
`CancellationTokenSource` objects that are used for timeouts (are created with timers or uses the `CancelAfter` method), can put pressure on the timer queue if not disposed.
❌ **BAD** This example does not dispose the `CancellationTokenSource` and as a result the timer stays in the queue for 10 seconds after each request is made.
```C#
public async Task<Stream> HttpClientAsyncWithCancellationBad()
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
using (var client = _httpClientFactory.CreateClient())
{
var response = await client.GetAsync("http://backend/api/1", cts.Token);
return await response.Content.ReadAsStreamAsync();
}
}
```
:white_check_mark: **GOOD** This example disposes the `CancellationTokenSource` and properly removes the timer from the queue.
```C#
public async Task<Stream> HttpClientAsyncWithCancellationGood()
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
using (var client = _httpClientFactory.CreateClient())
{
var response = await client.GetAsync("http://backend/api/1", cts.Token);
return await response.Content.ReadAsStreamAsync();
}
}
}
```
## Always flow `CancellationToken`(s) to APIs that take a `CancellationToken`
Cancellation is cooperative in .NET. Everything in the call-chain has to be explicitly passed the `CancellationToken` in order for it to work well. This means you need to explicitly pass the token into other APIs that take a token if you want cancellation to be most effective.
❌ **BAD** This example neglects to pass the `CancellationToken` to `Stream.ReadAsync` making the operation effectively not cancellable.
```C#
public async Task<string> DoAsyncThing(CancellationToken cancellationToken = default)
{
byte[] buffer = new byte[1024];
// We forgot to pass flow cancellationToken to ReadAsync
int read = await _stream.ReadAsync(buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer, 0, read);
}
```
:white_check_mark: **GOOD** This example passes the `CancellationToken` into `Stream.ReadAsync`.
```C#
public async Task<string> DoAsyncThing(CancellationToken cancellationToken = default)
{
byte[] buffer = new byte[1024];
// This properly flows cancellationToken to ReadAsync
int read = await _stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
return Encoding.UTF8.GetString(buffer, 0, read);
}
```
## Cancelling uncancellable operations
One of the coding patterns that appears when doing asynchronous programming is cancelling an uncancellable operation. This usually means creating another task that completes when a timeout or `CancellationToken` fires, and then using `Task.WhenAny` to detect a complete or cancelled operation.
### Using CancellationTokens
❌ **BAD** This example uses `Task.Delay(-1, token)` to create a `Task` that completes when the `CancellationToken` fires, but if it doesn't fire, there's no way to dispose the `CancellationTokenRegistration`. This can lead to a memory leak.
```C#
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
// There's no way to dispose the registration
var delayTask = Task.Delay(-1, cancellationToken);
var resultTask = await Task.WhenAny(task, delayTask);
if (resultTask == delayTask)
{
// Operation cancelled
throw new OperationCanceledException();
}
return await task;
}
```
:white_check_mark: **GOOD** This example disposes the `CancellationTokenRegistration` when one of the `Task(s)` complete.
```C#
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
// This disposes the registration as soon as one of the tasks trigger
using (cancellationToken.Register(state =>
{
((TaskCompletionSource<object>)state).TrySetResult(null);
},
tcs))
{
var resultTask = await Task.WhenAny(task, tcs.Task);
if (resultTask == tcs.Task)
{
// Operation cancelled
throw new OperationCanceledException(cancellationToken);
}
return await task;
}
}
```
:white_check_mark: **GOOD** Prefer [`Task.WaitAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitasync?view=net-6.0) on .NET >= 6;
### Using a timeout
❌ **BAD** This example does not cancel the timer even if the operation successfully completes. This means you could end up with lots of timers, which can flood the timer queue.
```C#
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout)
{
var delayTask = Task.Delay(timeout);
var resultTask = await Task.WhenAny(task, delayTask);
if (resultTask == delayTask)
{
// Operation cancelled
throw new OperationCanceledException();
}
return await task;
}
```
:white_check_mark: **GOOD** This example cancels the timer if the operation successfully completes.
```C#
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout)
{
using (var cts = new CancellationTokenSource())
{
var delayTask = Task.Delay(timeout, cts.Token);
var resultTask = await Task.WhenAny(task, delayTask);
if (resultTask == delayTask)
{
// Operation cancelled
throw new OperationCanceledException();
}
else
{
// Cancel the timer task so that it does not fire
cts.Cancel();
}
return await task;
}
}
```
:white_check_mark: **GOOD** Prefer [`Task.WaitAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitasync?view=net-6.0) on .NET >= 6;
## Always call `FlushAsync` on `StreamWriter`(s) or `Stream`(s) before calling `Dispose`
When writing to a `Stream` or `StreamWriter`, even if the asynchronous overloads are used for writing, the underlying data might be buffered. When data is buffered, disposing the `Stream` or `StreamWriter` via the `Dispose` method will synchronously write/flush, which results in blocking the thread and could lead to thread-pool starvation. Either use the asynchronous `DisposeAsync` method (for example via `await using`) or call `FlushAsync` before calling `Dispose`.
:bulb:**NOTE: This is only problematic if the underlying subsystem does IO.**
❌ **BAD** This example ends up blocking the request by writing synchronously to the HTTP-response body.
```C#
app.Run(async context =>
{
// The implicit Dispose call will synchronously write to the response body
using (var streamWriter = new StreamWriter(context.Response.Body))
{
await streamWriter.WriteAsync("Hello World");
}
});
```
:white_check_mark: **GOOD** This example asynchronously flushes any buffered data while disposing the `StreamWriter`.
```C#
app.Run(async context =>
{
// The implicit AsyncDispose call will flush asynchronously
await using (var streamWriter = new StreamWriter(context.Response.Body))
{
await streamWriter.WriteAsync("Hello World");
}
});
```
:white_check_mark: **GOOD** This example asynchronously flushes any buffered data before disposing the `StreamWriter`.
```C#
app.Run(async context =>
{
using (var streamWriter = new StreamWriter(context.Response.Body))
{
await streamWriter.WriteAsync("Hello World");
// Force an asynchronous flush
await streamWriter.FlushAsync();
}
});
```
## Prefer `async`/`await` over directly returning `Task`
There are benefits to using the `async`/`await` keyword instead of directly returning the `Task`:
- Asynchronous and synchronous exceptions are normalized to always be asynchronous.
- The code is easier to modify (consider adding a `using`, for example).
- Diagnostics of asynchronous methods are easier (debugging hangs etc).
- Exceptions thrown will be automatically wrapped in the returned `Task` instead of surprising the caller with an actual exception.
- Async locals will not leak out of async methods. If you set an async local in a non-async method, it will "leak" out of that call.
❌ **BAD** This example directly returns the `Task` to the caller.
```C#
public Task<int> DoSomethingAsync()
{
return CallDependencyAsync();
}
```
:white_check_mark: **GOOD** This examples uses async/await instead of directly returning the Task.
```C#
public async Task<int> DoSomethingAsync()
{
return await CallDependencyAsync();
}
```
:bulb:**NOTE: There are performance considerations when using an async state machine over directly returning the `Task`. It's always faster to directly return the `Task` since it does less work but you end up changing the behavior and potentially losing some of the benefits of the async state machine.**
## AsyncLocal\<T\>
Async locals are a way to store/retrieve ambient state throughout an application. This can be a *very* useful alternative to flowing explicit state everywhere, especially through call sites that you do not have much control over. While it is powerful, it is also dangerous if used incorrectly. Async locals are attached to the [execution context](https://docs.microsoft.com/en-us/dotnet/api/system.threading.executioncontext) which flows *everywhere implicitly*. Disabling execution context flow requires use of advanced APIs (typically prefixed with the Unsafe name). As such, there's very little control over what code will attempt to access these values.
### Creating an AsyncLocal\<T\>
If you can avoid async locals, do so by explicitly passing state around or using techniques like inversion of control.
If you cannot avoid it, it's best to make sure that anything put into an async local is:
1. Not disposable
2. Immutable/read only/thread safe
Lets look at 2 examples:
1. ❌ **BAD** A disposable object stored in an async local
```C#
using (var thing = new DisposableThing())
{
// Make the disposable object available ambiently
DisposableThing.Current = thing;
Dispatch();
// We're about to dispose the object so make sure nobody else captures this instance
DisposableThing.Current = null;
}
void Dispatch()
{
// Task.Run will capture the current execution context (which means async locals are captured in the callback)
_ = Task.Run(async () =>
{
// Delay for a second then log
await Task.Delay(1000);
Log();
});
}
void Log()
{
try
{
// Get the current value and make sure it's not null before reading the value
var thing = DisposableThing.Current;
if (thing is not null)
{
Console.WriteLine($"Logging ambient value {thing.Value}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Console.ReadLine();
class DisposableThing : IDisposable
{
private static readonly AsyncLocal<DisposableThing?> _current = new();
private bool _disposed;
public static DisposableThing? Current
{
get => _current.Value;
set
{
_current.Value = value;
}
}
public int Value
{
get
{
if (_disposed) throw new ObjectDisposedException(GetType().FullName);
return 1;
}
}
public void Dispose()
{
_disposed = true;
}
}
```
This above example will always result in an `ObjectDisposedException` being thrown. Even though the `Log` method defensively checks for null before logging the value, it has a reference to the disposed `DisposableThing`. Setting the `AsyncLocal<DisposableThing>` to null does not affect the code inside of `Log`, this is because the execution context is copy on write. This means that all future reads `DisposableThing.Current` will be null, but it won't affect any of the previous reads.
When we set `DisposableThing.Current = null;` we are making a new execution context, not mutating the one that was captured by `Task.Run`. To get a better understanding of this run the following code:
```C#
DisposableThing.Current = new DisposableThing();
Console.WriteLine("After setting thing " + ExecutionContext.Capture().GetHashCode());
DisposableThing.Current = null;
Console.WriteLine("After setting Current to null " + ExecutionContext.Capture().GetHashCode());
```
The hash code of the execution context is different each time we set a new value.
⚠️ It might be tempting to update the logic in `DisposableThing.Current` to mutate the original execution context instead of setting the async local directly ([StrongBox\<T\>](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.strongbox-1) is a reference type that stores the underlying T in a mutable field):
```C#
class DisposableThing : IDisposable
{
private static readonly AsyncLocal<StrongBox<DisposableThing?>> _current = new();
private bool _disposed;
public static DisposableThing? Current
{
get => _current.Value?.Value;
set
{
var box = _current.Value;
if (box is not null)
{
// Mutate the value in any execution context that was copied
box.Value = null;
}
if (value is not null)
{
_current.Value = new StrongBox<DisposableThing?>(value);
}
}
}
public int Value
{
get
{
if (_disposed) throw new ObjectDisposedException(GetType().FullName);
return 1;
}
}
public void Dispose()
{
_disposed = true;
}
}
```
This will have the desired effect and will set the value to null in any execution context that references this async local value.
```C#
DisposableThing.Current = new DisposableThing();
Console.WriteLine("After setting thing " + ExecutionContext.Capture().GetHashCode());
DisposableThing.Current = null;
Console.WriteLine("After setting Current to null " + ExecutionContext.Capture().GetHashCode());
```
⚠️ While this looks attractive, the reference to `DisposableThing.Current` might have still been captured before the value was set to null:
```C#
void Dispatch()
{
// Task.Run will capture the current execution context (which means async locals are captured in the callback)
_ = Task.Run(async () =>
{
// Get the current reference
var current = DisposableThing.Current;
// Delay for a second then log
await Task.Delay(1000);
Log(current);
});
}
void Log(DisposableThing thing)
{
try
{
Console.WriteLine($"Logging ambient value {thing.Value}");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
```
There's a race condition between the capture of the `DisposableThing`, the disposal of `DisposableThing` and setting `DisposableThing.Current` it to null. In the end, the code is unreliable and may fail at random. Don't store disposable objects in async locals.
2. ❌ **BAD** A non-thread safe object stored in an async local
```C#
AmbientValues.Current = new Dictionary<int, string>();
Parallel.For(0, 10, i =>
{
AmbientValues.Current[i] = "processing";
LogCurrentValues();
AmbientValues.Current[i] = "done";
});
void LogCurrentValues()
{
foreach (var pair in AmbientValues.Current)
{
Console.WriteLine(pair);
}
}
class AmbientValues
{
private static readonly AsyncLocal<Dictionary<int, string>> _current = new();
public static Dictionary<int, string> Current
{
get => _current.Value!;
set => _current.Value = value;
}
}
```
The above example stores a normal `Dictionary<int, string>` in an async local and does some parallel processing on it. While this may be obvious from the above example, async locals allow arbitrary code on arbitrary threads to access the execution context and thus any async locals associated with said context. As a result, it is important to assume that data can be accessed concurrently and should be made thread safe as a result.
```C#
class AmbientValues
{
private static readonly AsyncLocal<ConcurrentDictionary<int, string>> _current = new();
public static ConcurrentDictionary<int, string> Current
{
get => _current.Value!;
set => _current.Value = value;
}
}
```
:white_check_mark: **GOOD** The above uses a `ConcurrentDictionary<int, string>` which is thread safe.
### Don't leak your AsyncLocal\<T\>
Async locals flow across awaits automatically and can be captured by any API that explicitly calls `ExecutionContext.Capture`. The latter can lead to memory leaks in certain situations.
#### Common APIs that capture the ExecutionContext
APIs that run user callbacks usually capture the current execution context in order to preserve async locals between callback registration and execution. Here are examples of some APIs that do this:
- `Timer`
- `CancellationToken.Register`
- `new FileSystemWatcher`
- `SocketAsyncEventArgs`
- `Task.Run`
- `ThreadPool.QueueUserWorkItem`
❌ **BAD** Here's an example of an execution context leak that causes memory pressure because of a lifetime mismatch between the API capturing the execution context, and the lifetime of the data stored in the async local.
```C#
using System.Collections.Concurrent;
// Singleton cache
var cache = new NumberCache(TimeSpan.FromHours(1));
var executionContext = ExecutionContext.Capture();
// Simulate 10000 concurrent requests
Parallel.For(0, 10000, i =>
{
// Restore the initial ExecutionContext per "request"
ExecutionContext.Restore(executionContext!);
ChunkyObject.Current = new ChunkyObject();
cache.Add(i);
});
Console.WriteLine("Before GC: " + BytesAsString(GC.GetGCMemoryInfo().HeapSizeBytes));
Console.ReadLine();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("After GC: " + BytesAsString(GC.GetGCMemoryInfo().HeapSizeBytes));
Console.ReadLine();
static string BytesAsString(long bytes)
{
string[] suffix = { "B", "KB", "MB", "GB", "TB" };
int i;
double doubleBytes = 0;
for (i = 0; bytes / 1024 > 0; i++, bytes /= 1024)
{
doubleBytes = bytes / 1024.0;
}
return string.Format("{0:0.00} {1}", doubleBytes, suffix[i]);
}
public class NumberCache
{
private readonly ConcurrentDictionary<int, CancellationTokenSource> _cache = new ConcurrentDictionary<int, CancellationTokenSource>();
private TimeSpan _timeSpan;
public NumberCache(TimeSpan timeSpan)
{
_timeSpan = timeSpan;
}
public void Add(int key)
{
var cts = _cache.GetOrAdd(key, _ => new CancellationTokenSource());
// Delete entry on expiration
cts.Token.Register((_, _) => _cache.TryRemove(key, out _), null);
// Start count down
cts.CancelAfter(_timeSpan);
}
}
class ChunkyObject
{
private static readonly AsyncLocal<ChunkyObject?> _current = new();
// Stores lots of data (but it should be gen0)
private readonly string _data = new string('A', 1024 * 32);
public static ChunkyObject? Current
{
get => _current.Value;
set => _current.Value = value;
}
public string Data => _data;
}
```
The above example has a singleton `NumberCache` that stores numbers for an hour. We have a `ChunkyObject` which stores a 32K string in a field, and has an async local so that any code running may access the current `ChunkyObject`. This object should be collected when the `GC` runs, but instead, we're implicitly capturing the `ChunkyObject` in the `NumberCache` via `CancellationToken.Register`.
**Instead of just caching the number and a `CancellationTokenSource`, we're implicitly capturing and storing all async locals attached to the current execution context for an hour!**
Try running the sample locally. Running this on my machine reports numbers like this:
```
Before GC: 654.65 MB
After GC: 659.68 MB
```
Here's a look at the heap with those objects. You can see we have stored 10,000 ChunkyObjects, strings rooted by those chunky objects. The object graph looks like
CancellationTokenSource -> ExecutionContext -> AsyncLocalValueMap -> ChunkObject -> string.
<img width="758" alt="image" src="https://user-images.githubusercontent.com/95136/188351756-967f3d37-b302-49d3-ba04-595433c6949c.png">
With one small tweak to this code, we can avoid the implicit execution context capture.
:white_check_mark: **GOOD** Use `CancellationToken.UnsafeRegister` to avoid capturing the execution context and any async locals as part of the `NumberCache`:
```C#
public class NumberCache
{
private readonly ConcurrentDictionary<int, CancellationTokenSource> _cache = new ConcurrentDictionary<int, CancellationTokenSource>();
private TimeSpan _timeSpan;
public NumberCache(TimeSpan timeSpan)
{
_timeSpan = timeSpan;
}
public void Add(int key)
{
var cts = _cache.GetOrAdd(key, _ => new CancellationTokenSource());
// Delete entry on expiration
cts.Token.UnsafeRegister((_, _) => _cache.TryRemove(key, out _), null);
// Start count down
cts.CancelAfter(_timeSpan);
}
}
```
The GC numbers after this change:
```
Before GC: 10.32 MB
After GC: 5.10 MB
```
The heap looks like we'd expect. There's no execution context capture, so the `ChunkyObject` isn't stored.
<img width="752" alt="image" src="https://user-images.githubusercontent.com/95136/188352462-d7d627c6-e4e0-4487-b783-30880cc4916f.png">
:bulb: **NOTE: You have NO control over how APIs decide to store the execution context, but with this understanding, you should be able to minimize memory leaks by clearing the memory using the technique described in [Creating an AsyncLocal\<T\>](#creating-an-asynclocalt) section.**