如何在DelegateCommand中使用异步方法 [英] How to use async method in 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数据绑定文章,以详细了解 如果您确实需要执行异步命令(这种情况很少见),则可以直接使用 如果您选择直接使用 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, ...)
You can use 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 If you really do need an asynchronous command (which is much more rare), you can use If you do choose to use 这篇关于如何在DelegateCommand中使用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!async void
或构建异步命令类型,如我在我在async void
:
async Task
逻辑公开,或者至少对单元测试可用.DelegateTask
一样,必须正确处理委托中的所有异常.{ // 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
directly. However, a few notes from my experience...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).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.async void
directly:
async Task
logic public, or at least accessible to your unit tests.DelegateTask
, any exceptions from your delegate must be properly handled.