BennoDual
BennoDual

Reputation: 6259

ICommand.CanExecute async

I have a Command, which Check for CanExecute takes much of time. Now, I ask me, if it is possible to run the Method for CanExecute asynchronous?

Upvotes: 2

Views: 4049

Answers (4)

user572559
user572559

Reputation:

with ICommand implementations, checking CanExecute is purely optional, the only real benefit of using CanExecute is that some UI controls being bound to the command can listen to CanExecuteChanged event and Enable/Disable themselves. There're many ways you can achieve this.

You don't have to use CanExecute just for sake of following the conventions. Why can't you start your long ruinning validation in a separate thread to avoid UI hangining and do the operation at the end of?

Upvotes: -2

slugster
slugster

Reputation: 49974

No, you cannot directly run it asynchronously. Nor should you, you do not know when the binding subsystem is going to call it.

There is nothing stopping you from starting a background thread from within that function, but to be honest that would make very little sense. If your CanExecute code is taking that long to execute then you really need to re-evaluate what you are doing, whether that means redo the code, or redo the UI to remove the dependency on the CanExecute.

If you use the DelegateCommand<T> from Prism you can force anything bound to the command to re-evaluate the CanExecute when you choose. This can be done by calling the RaiseCanExecuteChanged() function on the command. If you then have a background thread running which calls this when necessary it should function in the manner you want.

Upvotes: 5

Henk Holterman
Henk Holterman

Reputation: 273179

CanExecute has to run on the GUI thread.

But you can simply implement this for yourself:

Use a Boolean property that is updated from a Thread. When it is set, also call NotifyPropertyChanged (for the Command).

It is probably best to default this property to false, but that depend on your domain logic.

Upvotes: 1

dowhilefor
dowhilefor

Reputation: 11051

Well it is possible. You should use the CanExecutedChanged. Do your long lasting check in the background(you could use BackgroundWorker), store the result if you can execute or not, fire the event and just return the cached value in your CanExecute.

Upvotes: 6

Related Questions