-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAbstractAsyncProcessorBase.cs
More file actions
167 lines (141 loc) · 4.78 KB
/
Copy pathAbstractAsyncProcessorBase.cs
File metadata and controls
167 lines (141 loc) · 4.78 KB
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
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using EnumerableAsyncProcessor.Interfaces;
using EnumerableAsyncProcessor.Validation;
namespace EnumerableAsyncProcessor.RunnableProcessors.Abstract;
public abstract class AbstractAsyncProcessorBase : IAsyncProcessor, IAsyncDisposable, IDisposable
{
protected abstract IEnumerable<TaskCompletionSource> EnumerableTaskCompletionSources { get; }
protected readonly CancellationToken CancellationToken;
[field: MaybeNull, AllowNull]
private IEnumerable<Task> EnumerableTasks => field ??= EnumerableTaskCompletionSources.Select(x => x.Task);
private readonly CancellationTokenSource _cancellationTokenSource;
private volatile bool _disposed;
private readonly object _disposeLock = new();
[field: AllowNull, MaybeNull]
private Task OverallTask => field ??= Task.WhenAll(EnumerableTasks);
protected AbstractAsyncProcessorBase(CancellationTokenSource cancellationTokenSource)
{
ValidationHelper.ValidateCancellationTokenSource(cancellationTokenSource);
CancellationToken = cancellationTokenSource.Token;
CancellationToken.Register(CancelAll);
CancellationToken.ThrowIfCancellationRequested();
_cancellationTokenSource = cancellationTokenSource;
}
internal abstract Task Process();
public IEnumerable<Task> GetEnumerableTasks()
{
return EnumerableTasks;
}
public TaskAwaiter GetAwaiter()
{
return WaitAsync().GetAwaiter();
}
public Task WaitAsync()
{
return OverallTask;
}
public void CancelAll()
{
if (_disposed)
return;
if (!_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
}
foreach (var tcs in EnumerableTaskCompletionSources)
{
tcs.TrySetCanceled(CancellationToken);
}
}
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
lock (_disposeLock)
{
if (_disposed)
return;
_disposed = true;
}
// Allow derived classes to dispose their resources first
await DisposeAsyncCore().ConfigureAwait(false);
// Cancel all operations
CancelAll();
// Wait for all running tasks to complete with timeout
try
{
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var allTasks = EnumerableTasks.ToList();
if (allTasks.Count > 0)
{
var completionTasks = allTasks.Select(async task =>
{
try
{
await task.WaitAsync(timeoutCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Expected when cancelled - ignore
}
catch (Exception)
{
// Task exceptions are expected - ignore during disposal
}
}).ToList();
if (completionTasks.Count > 0)
{
try
{
await Task.WhenAll(completionTasks).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Timeout occurred - continue with disposal
}
}
}
}
catch (Exception)
{
// Swallow exceptions during disposal cleanup
}
// Dispose the cancellation token source
try
{
_cancellationTokenSource.Dispose();
}
catch (Exception)
{
// Swallow disposal exceptions
}
GC.SuppressFinalize(this);
}
protected virtual ValueTask DisposeAsyncCore()
{
#if NET6_0_OR_GREATER
return ValueTask.CompletedTask;
#else
return new ValueTask(Task.CompletedTask);
#endif
}
public void Dispose()
{
// Use Task.Run to avoid deadlocks by running async disposal on thread pool
// Add timeout to prevent indefinite blocking
try
{
var disposeTask = Task.Run(async () => await DisposeAsync().ConfigureAwait(false));
if (!disposeTask.Wait(TimeSpan.FromSeconds(30)))
{
// Log warning if disposal times out, but don't throw
// as per IDisposable pattern
}
}
catch
{
// Suppress exceptions during disposal as per IDisposable pattern
}
}
}