Skip to content

Instantly share code, notes, and snippets.

@tanaka-takayoshi
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaka-takayoshi/05dd002e914125896700 to your computer and use it in GitHub Desktop.
Save tanaka-takayoshi/05dd002e914125896700 to your computer and use it in GitHub Desktop.
Producer-consumer pattern solution for using Rx in PowerShell Cmdlet class
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