Last active
August 29, 2015 14:10
-
-
Save tanaka-takayoshi/05dd002e914125896700 to your computer and use it in GitHub Desktop.
Producer-consumer pattern solution for using Rx in PowerShell Cmdlet class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.Management.Automation; | |
using ObservableCmdlet.Lib; | |
namespace ObservableCmdletSample | |
{ | |
[Cmdlet("Invoke", "HelloRx")] | |
public class HelloRxCmdlet : Cmdlet | |
{ | |
protected override void ProcessRecord() | |
{ | |
var lib = new Library(); | |
Exception exception = null; | |
var q = new BlockingCollection<Action>(); | |
var observer = | |
lib.InvokeHello() | |
.Subscribe( | |
status => q.Add(() => | |
{ | |
WriteObject(status); | |
WriteProgress(new ProgressRecord(1, "Progress", status)); | |
}), | |
e => | |
{ | |
exception = e; | |
q.CompleteAdding(); | |
}, | |
q.CompleteAdding); | |
foreach (var item in q.GetConsumingEnumerable()) | |
{ | |
item(); | |
} | |
if (exception != null) | |
ThrowTerminatingError(new ErrorRecord(exception, "", ErrorCategory.OperationStopped, null)); | |
WriteObject(true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment