由于 StandardOutput 不是 react 性的,我需要一种方法来观察它。
我知道 Process 类公开了一个事件,用于在写入输出时接收通知
所以我使用这个扩展方法来获取标准输出的 IObservable

public static class ProcessExtensions
{
    public static IObservable<string> StandardOutputObservable(this Process process)
    {
        process.EnableRaisingEvents = true;
        process.StartInfo.RedirectStandardOutput = true;

        var received = Observable.FromEventPattern<DataReceivedEventHandler,DataReceivedEventArgs>(
            handler => handler.Invoke,
            h => process.OutputDataReceived += h,
            h => process.OutputDataReceived -= h)
            .TakeUntil(Observable.FromEventPattern(
                h => process.Exited += h,
                h => process.Exited -= h))
            .Select(e => e.EventArgs.Data);

        process.BeginOutputReadLine();

        return received;

        /* Or if cancellation is important to you...
        return Observable.Create<string>(observer =>
            {
                var cancel = Disposable.Create(process.CancelOutputRead);

                return new CompositeDisposable(
                    cancel,
                    received.Subscribe(observer));
            });
         */
    }
}

如发现 here
但是当我开始这个过程时
public sealed class ProgramHelper
{
    private readonly Process _program = new Process();
    public IObservable<string> ObservableOutput { get; private set; }

    public ProgramHelper(string programPath, string programArgs)
    {
        _program.StartInfo.FileName = programPath;
        _program.StartInfo.Arguments = programArgs;
    }

    public void StartProgram()
    {
        ConfigService.SaveConfig(
            new Config(
                new Uri(@"http://some.url.com")));

        _program.Start();

        ObservableOutput = _program.StandardOutputObservable();

    }
}

...

[TestFixture]
public class When_program_starts
{
    private ProgramHelper _program;

    [Test]
    public void It_should_not_complain()
    {
       //W
       Action act = () => _program.StartProgram();
       //T
       act.ShouldNotThrow<Exception>();
    }
}

我收到此错误:



感谢您的时间。

编辑:
将 ProgramHelper 编辑为
    public ProgramHelper(string programPath, string programArgs)
    {
        _program.StartInfo.FileName = programPath;
        _program.StartInfo.Arguments = programArgs;
        _program.EnableRaisingEvents = true;
        _program.StartInfo.UseShellExecute = false;
        _program.StartInfo.RedirectStandardOutput = true;
    }

但现在它抛出“访问被拒绝异常”。

似乎我无权以编程方式启动该过程;如果我从控制台启动 exe 它工作得很好。

最佳答案

在进程启动后,您正在改变 Process.StartInfo 属性。

Process.StartInfo MSDN documentation :

关于c# - 使用响应式(Reactive)扩展观察标准输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12040463/

10-17 01:55