private void AsyncRun(Func <bool> asyncAction) { try { using (_messages = new BlockingCollection <TaskCompletionSource <bool> >()) { // spawn the activity off in another thread. var task = IsInitialized ? Task.Factory.StartNew(asyncAction, TaskCreationOptions.LongRunning) : Task.Factory.StartNew(Init, TaskCreationOptions.LongRunning).ContinueWith(antecedent => { try { asyncAction(); } catch (Exception e) { e.Dump(); } }) ; // when the task is done, mark the msg queue as complete task.ContinueWith(antecedent => { if (_messages != null) { _messages.Complete(); } }); // process the queue of messages back in the main thread so that they // can properly access the non-thread-safe-things in cmdlet foreach (var message in _messages) { InvokeMessage(message); } } } finally { _messages = null; } }
protected override void Complete() { Results.Complete(); base.Complete(); }