C#进程处理抛出标准错误未被重定向

时间:2011-11-30 06:48:49

标签: c# dispose idisposable

我正在创建一个Process对象,以使用具有正确属性集的ProcessStartInfo运行进程。这一直有效,直到我考虑处理我的Process对象。最初我将它包装在一个使用块周围,然后失败,之后我在Exited Event Handler中显式调用Close和Dispose。

代码如下所示:

var processInfo = new ProcessStartInfo("program.exe", argument)
{
    RedirectStandardError = true,
    CreateNoWindow = true,
    UseShellExecute = false
};
var proc = new Process { StartInfo = processInfo, EnableRaisingEvents = true };
proc.Exited += EventHandler;
proc.Start();
proc.WaitForExit();

private static void EventHandler(object sender, EventArgs e)
{
    var p = sender as Process;
    if (p == null)
        return;
    var stdErr = p.StandardError.ReadToEnd();
    if (!string.IsNullOrEmpty(stdErr))
        Console.WriteLine(string.Format("Log:({0}) {1} ", p.ExitCode, stdErr));
    p.Close();
    p.Dispose();
}

当我添加p.Close()和p.Dispose()时,我收到以下错误:

System.InvalidOperationException : StandardError has not been redirected.
   at System.Diagnostics.Process.get_StandardError()

StackTrace如下:

Unhandled exception in remote appdomain: System.InvalidOperationException: StandardError has not been redirected.
   at System.Diagnostics.Process.get_StandardError()
   at namespace.EventHandler(Object sender, EventArgs e) in c:\BuildAgent\work\70df16b46ad15c54\Source\Blah.cs:line 318
   at System.Diagnostics.Process.OnExited()
   at System.Diagnostics.Process.RaiseOnExited()
   at System.Diagnostics.Process.CompletionCallback(Object context, Boolean wasSignaled)
   at System.Threading._ThreadPoolWaitOrTimerCallback.WaitOrTimerCallback_Context(Object state, Boolean timedOut)
   at System.Threading._ThreadPoolWaitOrTimerCallback.WaitOrTimerCallback_Context_f(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Object state, Boolean timedOut)

即使以下代码也会引发相同的异常:

var processInfo = new ProcessStartInfo("program.exe", argument)
{
    RedirectStandardError = true,
    CreateNoWindow = true,
    UseShellExecute = false
};
using(var proc = new Process { StartInfo = processInfo, EnableRaisingEvents =true })
{
    proc.Exited += EventHandler;
    proc.Start();
    proc.WaitForExit();
}

private static void EventHandler(object sender, EventArgs e)
{
    var p = sender as Process;
    if (p == null)
        return;
    var stdErr = p.StandardError.ReadToEnd();
    if (!string.IsNullOrEmpty(stdErr))
        Console.WriteLine(string.Format("Log:({0}) {1} ", p.ExitCode, stdErr));

}

0 个答案:

没有答案