Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.