Extensions for System.Threading.Tasks.Task
, inspired by John Thiriet's blog posts: Removing Async Void and MVVM - Going Async With AsyncCommand.
- AsyncAwaitBestPractices
- An extension method to safely fire-and-forget a
Task
:SafeFireAndForget
- Usage instructions below
- An extension method to safely fire-and-forget a
- AsyncAwaitBestPractices.MVVM
- Allows for
Task
to safely be used asynchronously withICommand
:IAsyncCommand : ICommand
AsyncCommand : IAsyncCommand
AsyncCommand<T> : IAsyncCommand
- Usage instructions below
- Allows for
- Available on NuGet: https://www.nuget.org/packages/AsyncAwaitBestPractices/
- Add to any project supporting .NET Standard 1.0
- Available on NuGet: https://www.nuget.org/packages/AsyncAwaitBestPractices.MVVM/
- Add to any project supporting .NET Standard 2.0
An extension method to safely fire-and-forget a Task
:
SafeFireAndForget
void HandleButtonTapped(object sender, EventArgs e)
{
// Allows the async Task method to safely run on a different thread while not awaiting its completion
ExampleAsyncMethod().SafeFireAndForget();
// HandleButtonTapped continues execution here while `ExampleAsyncMethod()` is running on a different thread
// ...
}
async Task ExampleAsyncMethod()
{
await Task.Delay(1000);
}
Allows for Task
to safely be used asynchronously with ICommand
:
AsyncCommand<T> : IAsyncCommand
AsyncCommand : IAsyncCommand
IAsyncCommand : ICommand
public class ExampleClass
{
public ExampleClass()
{
ExampleAsyncCommand = new AsyncCommand(ExampleAsyncMethod);
ExampleAsyncIntCommand = new AsyncCommand<int>(ExampleAsyncMethodWithIntParameter);
ExampleAsyncExceptionCommand = new AsyncCommand(ExampleAsyncMethodWithException, onException: ex => Console.WriteLine(ex.Message));
ExampleAsyncCommandNotReturningToTheCallingThread = new AsyncCommand(ExampleAsyncMethod, continueOnCapturedContext: false);
}
public IAsyncCommand ExampleAsyncCommand { get; }
public IAsyncCommand ExampleAsyncIntCommand { get; }
public IAsyncCommand ExampleAsyncExceptionCommand { get; }
public IAsyncCommand ExampleAsyncCommandNotReturningToTheCallingThread { get; }
async Task ExampleAsyncMethod()
{
await Task.Delay(1000);
}
async Task ExampleAsyncMethodWithIntParameter(int parameter)
{
await Task.Delay(parameter);
}
async Task ExampleAsyncMethodWithException()
{
await Task.Delay(1000);
throw new Exception();
}
void ExecuteCommands()
{
ExampleAsyncCommand.Execute(null);
ExampleAsyncIntCommand.Execute(1000);
ExampleAsyncExceptionCommand.Execute(null);
ExampleAsyncCommandNotReturningToTheCallingThread.Execute(null);
}
}