Skip to content

Commit dba9c41

Browse files
committed
Implement FlowExceptionsToTaskScheduler option
1 parent 79204ab commit dba9c41

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

CommunityToolkit.Mvvm/Input/AsyncRelayCommand.cs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,14 @@ public bool CanExecute(object? parameter)
279279
/// <inheritdoc/>
280280
public void Execute(object? parameter)
281281
{
282-
_ = ExecuteAsync(parameter);
282+
Task executionTask = ExecuteAsync(parameter);
283+
284+
// If exceptions shouldn't flow to the task scheduler, await the resulting task. This is
285+
// delegated to a separate method to keep this one more compact in case the option is set.
286+
if ((this.options & AsyncRelayCommandOptions.FlowExceptionsToTaskScheduler) == 0)
287+
{
288+
AwaitAndThrowIfFailed(executionTask);
289+
}
283290
}
284291

285292
/// <inheritdoc/>
@@ -323,4 +330,13 @@ public void Cancel()
323330
PropertyChanged?.Invoke(this, IsCancellationRequestedChangedEventArgs);
324331
}
325332
}
333+
334+
/// <summary>
335+
/// Awaits an input <see cref="Task"/> and throws an exception on the calling context, if the task fails.
336+
/// </summary>
337+
/// <param name="executionTask">The input <see cref="Task"/> instance to await.</param>
338+
internal static async void AwaitAndThrowIfFailed(Task executionTask)
339+
{
340+
await executionTask;
341+
}
326342
}

CommunityToolkit.Mvvm/Input/AsyncRelayCommand{T}.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,13 +275,18 @@ public bool CanExecute(object? parameter)
275275
[MethodImpl(MethodImplOptions.AggressiveInlining)]
276276
public void Execute(T? parameter)
277277
{
278-
_ = ExecuteAsync(parameter);
278+
Task executionTask = ExecuteAsync(parameter);
279+
280+
if ((this.options & AsyncRelayCommandOptions.FlowExceptionsToTaskScheduler) == 0)
281+
{
282+
AsyncRelayCommand.AwaitAndThrowIfFailed(executionTask);
283+
}
279284
}
280285

281286
/// <inheritdoc/>
282287
public void Execute(object? parameter)
283288
{
284-
_ = ExecuteAsync((T?)parameter);
289+
Execute((T?)parameter);
285290
}
286291

287292
/// <inheritdoc/>

0 commit comments

Comments
 (0)