Note that there are some explanatory texts on larger screens.

plurals
  1. POAsynchronous WPF Commands
    text
    copied!<p><strong><em>Note</strong>: The code in this question is part of <a href="http://www.codeplex.com/desleeper" rel="noreferrer">deSleeper</a> if you want the full source.</em></p> <p>One of the things I wanted out of commands was a baked design for asynchronous operations. I wanted the button pressed to disable while the command was executing, and come back when complete. I wanted the actual work to be performed in a ThreadPool work item. And lastly, I wanted a way to handle any errors that occurred during the asynchronous processing.</p> <p>My solution was an AsyncCommand:</p> <pre><code>public abstract class AsyncCommand : ICommand { public event EventHandler CanExecuteChanged; public event EventHandler ExecutionStarting; public event EventHandler&lt;AsyncCommandCompleteEventArgs&gt; ExecutionComplete; public abstract string Text { get; } private bool _isExecuting; public bool IsExecuting { get { return _isExecuting; } private set { _isExecuting = value; if (CanExecuteChanged != null) CanExecuteChanged(this, EventArgs.Empty); } } protected abstract void OnExecute(object parameter); public void Execute(object parameter) { try { IsExecuting = true; if (ExecutionStarting != null) ExecutionStarting(this, EventArgs.Empty); var dispatcher = Dispatcher.CurrentDispatcher; ThreadPool.QueueUserWorkItem( obj =&gt; { try { OnExecute(parameter); if (ExecutionComplete != null) dispatcher.Invoke(DispatcherPriority.Normal, ExecutionComplete, this, new AsyncCommandCompleteEventArgs(null)); } catch (Exception ex) { if (ExecutionComplete != null) dispatcher.Invoke(DispatcherPriority.Normal, ExecutionComplete, this, new AsyncCommandCompleteEventArgs(ex)); } finally { dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =&gt; IsExecuting = false)); } }); } catch (Exception ex) { IsExecuting = false; if (ExecutionComplete != null) ExecutionComplete(this, new AsyncCommandCompleteEventArgs(ex)); } } public virtual bool CanExecute(object parameter) { return !IsExecuting; } } </code></pre> <p>so the question is: Is all this necessary? I've noticed built in asynchronous support for data-binding, so why not command execution? Perhaps it's related to the parameter question, which is my next question.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload