-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAsyncDisposable.cs
55 lines (46 loc) · 1.18 KB
/
AsyncDisposable.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
using System;
using System.IO;
using System.Threading.Tasks;
class AsyncDisposable : IRunnable
{
public async Task Run()
{
using (var wrong = new WrongDisposable())
{
}
await using (var correct = new CorrectDisposable()
.ConfigureAwait(false))
{
}
// using (var correct = new CorrectDisposable())
// {
// }
}
class WrongDisposable : DisposableBase, IDisposable
{
public void Dispose()
{
Log();
// sync over async anti-pattern
stream.FlushAsync().GetAwaiter().GetResult();
stream.Dispose();
}
}
class CorrectDisposable : DisposableBase, IAsyncDisposable, IDisposable
{
public async ValueTask DisposeAsync()
{
Log();
await stream.FlushAsync().ConfigureAwait(false);
stream.Dispose();
// or
await stream.DisposeAsync().ConfigureAwait(false);
}
public void Dispose()
{
Log();
stream.Flush();
stream.Dispose();
}
}
}