Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async method in DelegateCommand

I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

{      // My view model constructor
       ... 
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}
like image 732
sorosh_sabz Avatar asked Apr 02 '17 10:04

sorosh_sabz


Video Answer


1 Answers

You can use async void directly. However, a few notes from my experience...

The structure of your code is: start asynchronous operation and then update UI with the results. This implies to me that you would be better served with a NotifyTask<T> kind of approach to asynchronous data binding, not commands. See my async MVVM data binding article for more about the design behind NotifyTask<T> (but note that the latest code has a bugfix and other enhancements).

If you really do need an asynchronous command (which is much more rare), you can use async void directly or build an async command type as I describe in my article on async MVVM commmands. I also have types to support this but the APIs for these are more in flux.

If you do choose to use async void directly:

  • Consider making your async Task logic public, or at least accessible to your unit tests.
  • Don't forget to handle exceptions properly. Just like a plain DelegateTask, any exceptions from your delegate must be properly handled.
like image 150
Stephen Cleary Avatar answered Oct 03 '22 21:10

Stephen Cleary