diff --git a/docs/mvvm/AsyncRelayCommand.md b/docs/mvvm/AsyncRelayCommand.md new file mode 100644 index 0000000..b59bf5a --- /dev/null +++ b/docs/mvvm/AsyncRelayCommand.md @@ -0,0 +1,87 @@ +--- +title: AsyncRelayCommand +author: Sergio0694 +description: An asynchronous command whose sole purpose is to relay its functionality to other objects by invoking delegates +keywords: windows 10, uwp, windows community toolkit, uwp community toolkit, uwp toolkit, mvvm, componentmodel, property changed, notification, binding, command, delegate, net core, net standard +dev_langs: + - csharp +--- + +# AsyncRelayCommand and AsyncRelayCommand<T> + +The [`AsyncRelayCommand`](https://docs.microsoft.com/dotnet/api/microsoft.toolkit.mvvm.input.AsyncRelayCommand) and [`AsyncRelayCommand`](https://docs.microsoft.com/dotnet/api/microsoft.toolkit.mvvm.input.AsyncRelayCommand-1) are `ICommand` implementations that extend the functionalities offered by `RelayCommand`, with support for asynchronous operations. + +## How they work + +`AsyncRelayCommand` and `AsyncRelayCommand` have the following main features: + +- They extend the functionalities of the non-asynchronous commands included in the library, with support for `Task`-returning delegates. +- They expose an `ExecutionTask` property that can be used to monitor the progress of a pending operation, and an `IsRunning` that can be used to check when an operation completes. This is particularly useful to bind a command to UI elements such as loading indicators. +- They implement the `IAsyncRelayCommand` and `IAsyncRelayCommand` interfaces, which means that viewmodel can easily expose commands using these to reduce the tight coupling between types. For instance, this makes it easier to replace a command with a custom implementation exposing the same public API surface, if needed. + +## Working with asynchronous commands + +Let's imagine a scenario similar to the one described in the `RelayCommand` sample, but a command executing an asynchronous operation: + +```csharp +public class MyViewModel : ObservableObject +{ + public MyViewModel() + { + DownloadTextCommand = new AsyncRelayCommand(DownloadText); + } + + public IAsyncRelayCommand DownloadTextCommand { get; } + + private Task DownloadText() + { + return WebService.LoadMyTextAsync(); + } +} +``` + +With the related UI code: + +```xml + + + + + + + + + + + + + +