如何在DelegateCommand中使用异步方法 [英] How to use async method in DelegateCommand

查看:521
本文介绍了如何在DelegateCommand中使用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将异步方法链接到Xamarin.Forms的棱镜框架中的委托命令,我的问题是怎么做?

以下解决方案正确吗?有陷阱吗? (僵局,UI缓慢或冻结,不良做法...)

{      // 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
}

解决方案

可以直接使用async void.但是,根据我的经验,有几点...

您的代码结构为:开始异步操作,然后使用结果更新UI.这对我来说意味着最好使用异步MVVM数据绑定文章,以详细了解(但请注意,最新代码具有错误修正和其他增强功能)./p>

如果您确实需要执行异步命令(这种情况很少见),则可以直接使用async void或构建异步命令类型,如我在我在异步MVVM命令.我也有类型来支持这一点,但是用于这些目的的API会不断变化.

如果您选择直接使用async void:

  • 考虑将您的async Task逻辑公开,或者至少对单元测试可用.
  • 别忘了正确处理异常.就像普通的DelegateTask一样,必须正确处理委托中的所有异常.

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
}

解决方案

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.

这篇关于如何在DelegateCommand中使用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆