Skip to content

ImanMesgaran/AsyncAwaitBestPractices

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

83 Commits
 
 
 
 
 
 
 
 

Repository files navigation

AsyncAwaitBestPractices

Build Status

Extensions for System.Threading.Tasks.Task, inspired by John Thiriet's blog posts: Removing Async Void and MVVM - Going Async With AsyncCommand.

  • AsyncAwaitBestPractices
  • AsyncAwaitBestPractices.MVVM
    • Allows for Task to safely be used asynchronously with ICommand:
      • IAsyncCommand : ICommand
      • AsyncCommand : IAsyncCommand
      • AsyncCommand<T> : IAsyncCommand
    • Usage instructions below

Setup

AsyncAwaitBestPractices

NuGet NuGet

AsyncAwaitBestPractices.MVVM

NuGet NuGet

Usage

AsyncAwaitBestPractices

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);
}

AsyncAwaitBestPractices.MVVM

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);
    }
}

Packages

No packages published

Languages

  • C# 100.0%