MVVM指示灯中的异步命令执行 [英] Async command execution in MVVM light

查看:63
本文介绍了MVVM指示灯中的异步命令执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么MVVM light缺少执行异步的命令?我相信在很多情况下这可能有用,所以我举一个例子.

可以说我们的UI包含一个包含多个屏幕的容器.用户可以关闭特定的屏幕,也可以关闭具有多个屏幕的容器.假设用户已经在容器上发出了关闭命令.反过来,容器在每个屏幕上调用close命令,并且它需要等待屏幕关闭.实际上,这可能意味着验证数据.因此,我们需要发出一个异步调用来防止UI变得无响应,并且我们还需要等待任务完成才能继续.

因此,如果我们在Command中有类似的内容

public RelayCommand CloseCommand
{
    get { return _closeCommand ?? _closeCommand = new RelayCommand( async () =>
    {
        foreach (var screen in Screens)
        {
            if (!await screen.CloseCommand.ExecuteAsync(null))
            {
                // do something
            }
        }
    }) }

}

我们还可以在屏幕上显示其他方法,但是我认为这应该是RelayCommand的任务,因为它已经存在于该方法中.

还是有不同的方法来处理这种情况?

解决方案

可能是因为有很多不同的方法可以做到;我在关于该主题的MSDN文章中描述了几种方法. >

异步生存期命令特别棘手.必须仔细考虑类似关闭"命令的内容.是否有迹象表明交易正在进行中?如果用户关闭了不止一次(特别是关闭"通常可以由OS或另一个应用程序启动,即使禁用了关闭按钮"),会发生什么情况?

I am wondering why is MVVM light missing command with async execution? I believe there are many cases where this could be useful, so let me name one.

Lets say that our UI contains one container that contains multiple screens. User can close a particular screen, or a container with multiple screens. Lets say that a user has issued a close command on the container. Container in return invokes close command on each screen, and it needs to wait for screen to be closed. This in practice can means validating data. saving, etc. For this reason we need to issue an async call to keep the UI from becoming unresponsive, and also we need to wait for task to complete, in order to continue.

So, if we have something like this in Command

public RelayCommand CloseCommand
{
    get { return _closeCommand ?? _closeCommand = new RelayCommand( async () =>
    {
        foreach (var screen in Screens)
        {
            if (!await screen.CloseCommand.ExecuteAsync(null))
            {
                // do something
            }
        }
    }) }

}

We could also expose additional method on screen, but in my opinion it should be task of RelayCommand, since it already exist there.

Or there is a different methodology to handle such scenario?

解决方案

Probably because there are many different ways of doing it; I describe a few approaches in my MSDN article on the subject.

Asynchronous lifetime commands are especially tricky. Something like a "close" command must be carefully considered. Is there some indication that a close is in progress? What happens if the user closes more than once ("close" in particular can often be initiated by an OS or another app even if a "close button" is disabled)?

这篇关于MVVM指示灯中的异步命令执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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