using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using System.Threading; using Lobster.Components.PowerShell; namespace Lobster.PowerShell { [System.ComponentModel.Composition.Export(typeof(IShellScript))] public class AsyncShellScript : ShellScriptBase { public override event Action<IShellScript> OperationCompleted; public AsyncShellScript() { syncContext = SynchronizationContext.Current ?? new SynchronizationContext(); } private SynchronizationContext syncContext; public override bool Run() { try { if (!IsValid) return false; // Invoke will end taking input parameters Pipeline.Input.Close(); Results = new Collection<object>(); Pipeline.Output.DataReady += new EventHandler(Output_DataReady); // execute the script Pipeline.InvokeAsync(); } catch (Exception e) { ValidityMessage = "Error in AsyncShellScript.Run: " + e.ToString(); IsValid = false; } return IsValid; } private Collection<object> internalResults = new Collection<object>(); void Output_DataReady(object sender, EventArgs e) { var c = Pipeline.Output.NonBlockingRead(); foreach (var i in c) { internalResults.Add(i.ImmediateBaseObject); } if (Pipeline.Output.EndOfPipeline) { Results = internalResults; // close the runspace Runspace.Close(); // Signal completion to owner (Switch to main thread) syncContext.Post((o) => { var oce = OperationCompleted; if (null != oce) { oce(this); } }, this); } } public override Lobster.Components.PowerShell.ShellScriptType Type { get { return Lobster.Components.PowerShell.ShellScriptType.Asynchronous; } } public override object Clone() { return new AsyncShellScript(); } } }
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)