gpt4 book ai didi

c# - 使用响应式扩展观察标准输出

转载 作者:行者123 更新时间:2023-11-30 15:37:55 25 4
gpt4 key购买 nike

由于 StandardOutput 不是被动的,我需要一种观察它的方法。我知道 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>();
}
}

我收到这个错误:

"StandardOut has not been redirected or the process hasn't started yet."

感谢您的宝贵时间。

编辑:将 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 :

You can change the parameters specified in the StartInfo property up to the time that you call the Start method on the process. After you start the process, changing the StartInfo values does not affect or restart the associated process.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com