forked from autofac/Autofac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncReleaseAction.cs
69 lines (60 loc) · 2.3 KB
/
AsyncReleaseAction.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
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Threading.Tasks;
namespace Autofac.Util
{
/// <summary>
/// Adapts an async action to the <see cref="IAsyncDisposable"/> interface.
/// </summary>
internal class AsyncReleaseAction<TLimit> : Disposable
{
private readonly Func<TLimit, ValueTask> _action;
private readonly Func<TLimit> _factory;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncReleaseAction{TLimit}"/> class.
/// </summary>
/// <param name="action">
/// The async action to execute on disposal.
/// </param>
/// <param name="factory">
/// A factory that retrieves the value on which the <paramref name="action" />
/// should be executed.
/// </param>
public AsyncReleaseAction(Func<TLimit, ValueTask> action, Func<TLimit> factory)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (factory == null) throw new ArgumentNullException(nameof(factory));
_action = action;
_factory = factory;
}
/// <inheritdoc/>
protected override async ValueTask DisposeAsync(bool disposing)
{
// Value retrieval for the disposal is deferred until
// disposal runs to ensure any calls to, say, .ReplaceInstance()
// during .OnActivating() will be accounted for.
if (disposing)
{
await _action(_factory()).ConfigureAwait(false);
}
base.Dispose(disposing);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
// Value retrieval for the disposal is deferred until
// disposal runs to ensure any calls to, say, .ReplaceInstance()
// during .OnActivating() will be accounted for.
if (disposing)
{
var vt = _action(_factory());
if (!vt.IsCompletedSuccessfully)
{
vt.ConfigureAwait(false).GetAwaiter().GetResult();
}
}
base.Dispose(disposing);
}
}
}