-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathAsyncRelayCommand.cs
More file actions
353 lines (293 loc) · 14.9 KB
/
Copy pathAsyncRelayCommand.cs
File metadata and controls
353 lines (293 loc) · 14.9 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel.__Internals;
using CommunityToolkit.Mvvm.Input.Internals;
#pragma warning disable CS0618, CA1001
namespace CommunityToolkit.Mvvm.Input;
/// <summary>
/// A command that mirrors the functionality of <see cref="RelayCommand"/>, with the addition of
/// accepting a <see cref="Func{TResult}"/> returning a <see cref="Task"/> as the execute
/// action, and providing an <see cref="ExecutionTask"/> property that notifies changes when
/// <see cref="ExecuteAsync"/> is invoked and when the returned <see cref="Task"/> completes.
/// </summary>
public sealed partial class AsyncRelayCommand : IAsyncRelayCommand, ICancellationAwareCommand
{
/// <summary>
/// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="ExecutionTask"/>.
/// </summary>
internal static readonly PropertyChangedEventArgs ExecutionTaskChangedEventArgs = new(nameof(ExecutionTask));
/// <summary>
/// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="CanBeCanceled"/>.
/// </summary>
internal static readonly PropertyChangedEventArgs CanBeCanceledChangedEventArgs = new(nameof(CanBeCanceled));
/// <summary>
/// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="IsCancellationRequested"/>.
/// </summary>
internal static readonly PropertyChangedEventArgs IsCancellationRequestedChangedEventArgs = new(nameof(IsCancellationRequested));
/// <summary>
/// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="IsRunning"/>.
/// </summary>
internal static readonly PropertyChangedEventArgs IsRunningChangedEventArgs = new(nameof(IsRunning));
/// <summary>
/// The <see cref="Func{TResult}"/> to invoke when <see cref="Execute"/> is used.
/// </summary>
private readonly Func<Task>? execute;
/// <summary>
/// The cancelable <see cref="Func{T,TResult}"/> to invoke when <see cref="Execute"/> is used.
/// </summary>
/// <remarks>Only one between this and <see cref="execute"/> is not <see langword="null"/>.</remarks>
private readonly Func<CancellationToken, Task>? cancelableExecute;
/// <summary>
/// The optional action to invoke when <see cref="CanExecute"/> is used.
/// </summary>
private readonly Func<bool>? canExecute;
/// <summary>
/// The options being set for the current command.
/// </summary>
private readonly AsyncRelayCommandOptions options;
/// <summary>
/// The <see cref="CancellationTokenSource"/> instance to use to cancel <see cref="cancelableExecute"/>.
/// </summary>
/// <remarks>This is only used when <see cref="cancelableExecute"/> is not <see langword="null"/>.</remarks>
private CancellationTokenSource? cancellationTokenSource;
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <inheritdoc/>
public event EventHandler? CanExecuteChanged;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> is <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<Task> execute)
{
ArgumentNullException.ThrowIfNull(execute);
this.execute = execute;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="options">The options to use to configure the async command.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> is <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<Task> execute, AsyncRelayCommandOptions options)
{
ArgumentNullException.ThrowIfNull(execute);
this.execute = execute;
this.options = options;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="cancelableExecute">The cancelable execution logic.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="cancelableExecute"/> is <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
this.cancelableExecute = cancelableExecute;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="cancelableExecute">The cancelable execution logic.</param>
/// <param name="options">The options to use to configure the async command.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="cancelableExecute"/> is <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute, AsyncRelayCommandOptions options)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
this.cancelableExecute = cancelableExecute;
this.options = options;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> or <paramref name="canExecute"/> are <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<Task> execute, Func<bool> canExecute)
{
ArgumentNullException.ThrowIfNull(execute);
ArgumentNullException.ThrowIfNull(canExecute);
this.execute = execute;
this.canExecute = canExecute;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
/// <param name="options">The options to use to configure the async command.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> or <paramref name="canExecute"/> are <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<Task> execute, Func<bool> canExecute, AsyncRelayCommandOptions options)
{
ArgumentNullException.ThrowIfNull(execute);
ArgumentNullException.ThrowIfNull(canExecute);
this.execute = execute;
this.canExecute = canExecute;
this.options = options;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="cancelableExecute">The cancelable execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="cancelableExecute"/> or <paramref name="canExecute"/> are <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute, Func<bool> canExecute)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
ArgumentNullException.ThrowIfNull(canExecute);
this.cancelableExecute = cancelableExecute;
this.canExecute = canExecute;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class.
/// </summary>
/// <param name="cancelableExecute">The cancelable execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
/// <param name="options">The options to use to configure the async command.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="cancelableExecute"/> or <paramref name="canExecute"/> are <see langword="null"/>.</exception>
public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute, Func<bool> canExecute, AsyncRelayCommandOptions options)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
ArgumentNullException.ThrowIfNull(canExecute);
this.cancelableExecute = cancelableExecute;
this.canExecute = canExecute;
this.options = options;
}
private Task? executionTask;
/// <inheritdoc/>
public Task? ExecutionTask
{
get => this.executionTask;
private set
{
if (ReferenceEquals(this.executionTask, value))
{
return;
}
this.executionTask = value;
PropertyChanged?.Invoke(this, ExecutionTaskChangedEventArgs);
PropertyChanged?.Invoke(this, IsRunningChangedEventArgs);
bool isAlreadyCompletedOrNull = value?.IsCompleted ?? true;
if (this.cancellationTokenSource is not null)
{
PropertyChanged?.Invoke(this, CanBeCanceledChangedEventArgs);
PropertyChanged?.Invoke(this, IsCancellationRequestedChangedEventArgs);
}
// The branch is on a condition evaluated before raising the events above if
// needed, to avoid race conditions with a task completing right after them.
if (isAlreadyCompletedOrNull)
{
return;
}
static async void MonitorTask(AsyncRelayCommand @this, Task task)
{
await task.GetAwaitableWithoutEndValidation();
if (ReferenceEquals(@this.executionTask, task))
{
@this.PropertyChanged?.Invoke(@this, ExecutionTaskChangedEventArgs);
@this.PropertyChanged?.Invoke(@this, IsRunningChangedEventArgs);
if (@this.cancellationTokenSource is not null)
{
@this.PropertyChanged?.Invoke(@this, CanBeCanceledChangedEventArgs);
}
if ((@this.options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0)
{
@this.CanExecuteChanged?.Invoke(@this, EventArgs.Empty);
}
}
}
MonitorTask(this, value!);
}
}
/// <inheritdoc/>
public bool CanBeCanceled => IsRunning && this.cancellationTokenSource is { IsCancellationRequested: false };
/// <inheritdoc/>
public bool IsCancellationRequested => this.cancellationTokenSource is { IsCancellationRequested: true };
/// <inheritdoc/>
public bool IsRunning => ExecutionTask is { IsCompleted: false };
/// <inheritdoc/>
bool ICancellationAwareCommand.IsCancellationSupported => this.execute is null;
/// <inheritdoc/>
public void NotifyCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanExecute(object? parameter)
{
bool canExecute = this.canExecute?.Invoke() != false;
return canExecute && ((this.options & AsyncRelayCommandOptions.AllowConcurrentExecutions) != 0 || ExecutionTask is not { IsCompleted: false });
}
/// <inheritdoc/>
public void Execute(object? parameter)
{
Task executionTask = ExecuteAsync(parameter);
// If exceptions shouldn't flow to the task scheduler, await the resulting task. This is
// delegated to a separate method to keep this one more compact in case the option is set.
if ((this.options & AsyncRelayCommandOptions.FlowExceptionsToTaskScheduler) == 0)
{
AwaitAndThrowIfFailed(executionTask);
}
}
/// <inheritdoc/>
public Task ExecuteAsync(object? parameter)
{
Task executionTask;
if (this.execute is not null)
{
// Non cancelable command delegate
executionTask = ExecutionTask = this.execute();
}
else
{
// Cancel the previous operation, if one is pending
this.cancellationTokenSource?.Cancel();
CancellationTokenSource cancellationTokenSource = this.cancellationTokenSource = new();
// Invoke the cancelable command delegate with a new linked token
executionTask = ExecutionTask = this.cancelableExecute!(cancellationTokenSource.Token);
}
// If concurrent executions are disabled, notify the can execute change as well
if ((this.options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0)
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
return executionTask;
}
/// <inheritdoc/>
public void Cancel()
{
if (this.cancellationTokenSource is CancellationTokenSource { IsCancellationRequested: false } cancellationTokenSource)
{
cancellationTokenSource.Cancel();
PropertyChanged?.Invoke(this, CanBeCanceledChangedEventArgs);
PropertyChanged?.Invoke(this, IsCancellationRequestedChangedEventArgs);
}
}
/// <summary>
/// Awaits an input <see cref="Task"/> and throws an exception on the calling context, if the task fails.
/// </summary>
/// <param name="executionTask">The input <see cref="Task"/> instance to await.</param>
internal static async void AwaitAndThrowIfFailed(Task executionTask)
{
// Note: this method is purposefully an async void method awaiting the input task. This is done so that
// if an async relay command is invoked synchronously (ie. when Execute is called, eg. from a binding),
// exceptions in the wrapped delegate will not be ignored or just become visible through the ExecutionTask
// property, but will be rethrown in the original synchronization context by default. This makes the behavior
// more consistent with how normal commands work (where exceptions are also just normally propagated to the
// caller context), and avoids getting an app into an inconsistent state in case a method faults without
// other components being notified. It is also possible to not await this task and to instead ignore exceptions
// and then inspect them manually from the ExecutionTask property, by constructing an async command instance
// using the AsyncRelayCommandOptions.FlowExceptionsToTaskScheduler option. That will cause this call to
// be skipped, and exceptions will just either normally be available through that property, or will otherwise
// flow to the static TaskScheduler.UnobservedTaskException event if otherwise unobserved (eg. for logging).
await executionTask;
}
}