/// <summary> /// Executes the specified <see cref="Action"/> synchronously on the UI thread. /// </summary> /// <param name="action">The delegate to invoke.</param> public void Invoke( Action action ) { if( action.NullReference() ) throw new ArgumentNullException().StoreFileLine(); #if !SILVERLIGHT this.dispatcher.Invoke(action, this.priority); #else // NOTE: code segment originally from Caliburn.Micro var waitHandle = new ManualResetEvent(initialState: false); // initialState = non-signaled Exception exception = null; this.dispatcher.BeginInvoke(() => { try { action(); } catch( Exception ex ) { exception = ex; } waitHandle.Set(); }); waitHandle.WaitOne(); if( exception.NotNullReference() ) throw new System.Reflection.TargetInvocationException("An error occurred while dispatching a call to the UI Thread", exception).StoreFileLine(); #endif }
/// <summary> /// Executes the specified <see cref="Action"/> asynchronously on the UI thread. /// </summary> /// <param name="action">The delegate to invoke.</param> /// <returns>The <see cref="Task"/> representing the operation.</returns> public Task InvokeAsync( Action action ) { if( action.NullReference() ) throw new ArgumentNullException().StoreFileLine(); #if MECHANICAL_NET4 var tsc = new TaskCompletionSource<object>(); action = () => { try { action(); tsc.SetResult(null); // the Completed event would probably work just as well } catch( Exception ex ) { tsc.SetException(ex); } }; var op = this.dispatcher.BeginInvoke(action, this.priority, Parameters); op.Aborted += ( s, e ) => tsc.SetCanceled(); // DispatcherOperations can be aborted, before code starts executing (since we don't keep a reference to it, this should only happen if the Dispatcher is shut down, before execution starts) return tsc.Task; #elif SILVERLIGHT var tsc = new TaskCompletionSource<object>(); var op = this.dispatcher.BeginInvoke(() => { try { action(); tsc.SetResult(null); } catch( Exception ex ) { tsc.SetException(ex); } }); return tsc.Task; #else return this.dispatcher.InvokeAsync(action, this.priority).Task; #endif }
/// <summary> /// Initializes a new instance of the <see cref="DelegateCommand"/> class. /// </summary> /// <param name="execute">The delegate invoked by Execute.</param> /// <param name="canExecute">The delegate invoked by CanExecute.</param> public DelegateCommand( Action execute, Func<bool> canExecute = null ) : this( execute.NullReference() ? (Action<object>)null : new Action<object>(param => execute()), canExecute.NullReference() ? (Func<object, bool>)null : new Func<object, bool>(param => canExecute())) { }