1
+ using System ;
2
+ using System . Collections . Concurrent ;
3
+ using System . Collections . Generic ;
4
+ using System . Threading ;
5
+ using System . Threading . Tasks ;
6
+
7
+ namespace dotnetCampus . Threading . Reentrancy
8
+ {
9
+ /// <summary>
10
+ /// 执行当前队列中的最后一个任务,并对所有当前队列任务赋值该任务结果。
11
+ /// </summary>
12
+ /// <typeparam name="TParameter">
13
+ /// 重入任务中单次执行时所使用的参数。
14
+ /// 此重入策略不会忽略任何参数。
15
+ /// </typeparam>
16
+ /// <typeparam name="TReturn">
17
+ /// 重入任务中单次执行时所得到的返回值。
18
+ /// 此重入策略不会忽略任何返回值。
19
+ /// </typeparam>
20
+ public sealed class KeepLastReentrancyTask < TParameter , TReturn > : ReentrancyTask < TParameter , TReturn >
21
+ {
22
+ /// <summary>
23
+ /// 用于原子操作判断当前是否正在执行队列中的可重入任务。
24
+ /// 1 表示当前正在执行可重入任务;0 表示不确定。
25
+ /// 不可使用 bool 类型,因为 bool 类型无法执行可靠的原子操作。
26
+ /// </summary>
27
+ private volatile int _isRunning ;
28
+
29
+ /// <summary>
30
+ /// 由于原子操作仅提供高性能的并发处理而不保证准确性,因此需要一个锁来同步 <see cref="_isRunning"/> 中值为 0 时所指的不确定情况。
31
+ /// 不能使用一个锁来同步所有情况是因为在锁中使用 async/await 是不安全的,因此避免在锁中执行异步任务;我们使用原子操作来判断异步任务的执行条件。
32
+ /// </summary>
33
+ private readonly object _locker = new object ( ) ;
34
+
35
+ /// <summary>
36
+ /// 使用一个并发队列来表示目前已加入到队列中的全部可重入任务。
37
+ /// 因为我们的 <see cref="_locker"/> 不能锁全部队列操作(原因见 <see cref="_locker"/>),因此需要使用并发队列。
38
+ /// </summary>
39
+ private readonly ConcurrentQueue < TaskWrapper > _queue = new ConcurrentQueue < TaskWrapper > ( ) ;
40
+
41
+ /// <summary>
42
+ /// 使用一个队列表示当前执行任务开始时所有需要进行赋值结果的任务。
43
+ /// </summary>
44
+ private readonly Queue < TaskWrapper > _skipQueue = new Queue < TaskWrapper > ( ) ;
45
+
46
+ /// <summary>
47
+ /// 创建以KeepLast策略执行的可重入任务。
48
+ /// </summary>
49
+ /// <param name="task">可重入任务本身。</param>
50
+ public KeepLastReentrancyTask ( Func < TParameter , Task < TReturn > > task ) : base ( task ) { }
51
+
52
+ /// <summary>
53
+ /// 以KeepLast策略执行重入任务,并获取此次重入任务的返回值。
54
+ /// 此重入策略会确保执行当前队列中的最后一个任务,并对所有当前队列任务赋值该任务结果。
55
+ /// </summary>
56
+ /// <param name="arg">此次重入任务使用的参数。</param>
57
+ /// <returns>重入任务本次执行的返回值。</returns>
58
+ public override Task < TReturn > InvokeAsync ( TParameter arg )
59
+ {
60
+ var wrapper = new TaskWrapper ( ( ) => RunCore ( arg ) ) ;
61
+ _queue . Enqueue ( wrapper ) ;
62
+ Run ( ) ;
63
+ return wrapper . AsTask ( ) ;
64
+ }
65
+
66
+ /// <summary>
67
+ /// 以KeepLast策略执行重入任务。此方法确保线程安全。
68
+ /// </summary>
69
+ private async void Run ( )
70
+ {
71
+ var isRunning = Interlocked . CompareExchange ( ref _isRunning , 1 , 0 ) ;
72
+ if ( isRunning is 1 )
73
+ {
74
+ lock ( _locker )
75
+ {
76
+ if ( _isRunning is 1 )
77
+ {
78
+ // 当前已经在执行队列,因此无需继续执行。
79
+ return ;
80
+ }
81
+ }
82
+ }
83
+
84
+ //下面这段是在临界区执行的,不存在多线程问题
85
+ var hasTask = true ;
86
+ while ( hasTask )
87
+ {
88
+ TaskWrapper runTask = null ;
89
+ // 当前还没有任何队列开始执行,因此需要开始执行队列。
90
+ while ( _queue . TryDequeue ( out var wrapper ) )
91
+ {
92
+ //所有任务项转入执行队列
93
+ if ( runTask != null )
94
+ {
95
+ _skipQueue . Enqueue ( runTask ) ;
96
+ }
97
+
98
+ runTask = wrapper ;
99
+ }
100
+
101
+ if ( runTask != null )
102
+ {
103
+ // 内部已包含异常处理,因此外面可以无需捕获或者清理。
104
+ await runTask . RunAsync ( ) . ConfigureAwait ( false ) ;
105
+ //完成后对等待队列中的项赋值
106
+ if ( runTask . Exception != null )
107
+ {
108
+ SetException ( runTask . Exception ) ;
109
+ }
110
+ else
111
+ {
112
+ SetResult ( runTask . Result ) ;
113
+ }
114
+ }
115
+
116
+
117
+ lock ( _locker )
118
+ {
119
+ hasTask = _queue . TryPeek ( out _ ) ;
120
+ if ( ! hasTask )
121
+ {
122
+ //退出临界区
123
+ _isRunning = 0 ;
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+
130
+ private void SetException ( Exception exception )
131
+ {
132
+ while ( _skipQueue . Count > 0 )
133
+ {
134
+ var taskWrapper = _skipQueue . Dequeue ( ) ;
135
+ taskWrapper . SetException ( exception ) ;
136
+ }
137
+ }
138
+
139
+ private void SetResult ( TReturn result )
140
+ {
141
+ while ( _skipQueue . Count > 0 )
142
+ {
143
+ var taskWrapper = _skipQueue . Dequeue ( ) ;
144
+ taskWrapper . SetResult ( result ) ;
145
+ }
146
+ }
147
+
148
+ /// <summary>
149
+ /// 包装一个异步任务,以便在可以执行此异步任务的情况下可以在其他方法中监视其完成情况。
150
+ /// </summary>
151
+ private class TaskWrapper
152
+ {
153
+ /// <summary>
154
+ /// 创建一个任务包装。
155
+ /// </summary>
156
+ internal TaskWrapper ( Func < Task < TReturn > > workingTask )
157
+ {
158
+ _taskSource = new TaskCompletionSource < TReturn > ( ) ;
159
+ _task = workingTask ;
160
+ }
161
+
162
+ private readonly TaskCompletionSource < TReturn > _taskSource ;
163
+ private readonly Func < Task < TReturn > > _task ;
164
+
165
+ public TReturn Result { get ; set ; }
166
+ public Exception Exception { get ; set ; }
167
+
168
+ /// <summary>
169
+ /// 执行此异步任务。
170
+ /// </summary>
171
+ internal async Task RunAsync ( )
172
+ {
173
+ try
174
+ {
175
+ var task = _task ( ) ;
176
+ if ( task is null )
177
+ {
178
+ throw new InvalidOperationException ( "在指定 KeepLastReentrancyTask 的任务时,方法内不允许返回 null。请至少返回 Task.FromResult<object>(null)。" ) ;
179
+ }
180
+ var result = await task . ConfigureAwait ( false ) ;
181
+ _taskSource . SetResult ( result ) ;
182
+ Result = result ;
183
+ }
184
+ #pragma warning disable CA1031 // 异常已经被通知到异步代码中,因此此处无需处理异常。
185
+ catch ( Exception ex )
186
+ {
187
+ _taskSource . SetException ( ex ) ;
188
+ Exception = ex ;
189
+ }
190
+ #pragma warning restore CA1031 // 异常已经被通知到异步代码中,因此此处无需处理异常。
191
+ }
192
+
193
+ public void SetResult ( TReturn result )
194
+ {
195
+ if ( _taskSource . Task . IsCompleted || _taskSource . Task . IsFaulted )
196
+ {
197
+ return ;
198
+ }
199
+
200
+ _taskSource . SetResult ( result ) ;
201
+ }
202
+
203
+ public void SetException ( Exception exception )
204
+ {
205
+ if ( _taskSource . Task . IsCompleted || _taskSource . Task . IsFaulted )
206
+ {
207
+ return ;
208
+ }
209
+
210
+ _taskSource . SetException ( exception ) ;
211
+ }
212
+
213
+ /// <summary>
214
+ /// 将此异步包装器作为 <see cref="Task"/> 使用,以便获得 async/await 特性。
215
+ /// </summary>
216
+ internal Task < TReturn > AsTask ( ) => _taskSource . Task ;
217
+ }
218
+ }
219
+ }
0 commit comments