开发者

MVVM Light : RelayCommand : reuse the command or create a new instance?

When defining a RelayCommand in the ViewModel, this is normally done using once [lazy or in constructor] (see here for examples).

But is this safe ? What if multiple RelayCommands from the same instance are queued (multiple clicks from same button on the GUI), and for the first command the 'CanExecute' is changed to false, will the other queued commands also be cancelled ? I can imagine that this not th开发者_JS百科e correct behavior ?


Your execute action should double check whether the command can execute or not. CanExecute is a hint for anything binding to the command, but your ViewModel shouldn't make any assumptions about how the execute action is being called.


Multiple commands won't be queued. The RelayCommand is data-bound so it will be executed on the UI thread. There is only one UI thread, so one instance of the RelayCommand would have to finish execution before the next click entered. If you have long-running operations, you'll typically disable the command and kick of an asynchronous operation or spawn a background job, and then when the UI is released, the command will already be disabled before the next click is processed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜