C# 如何在保留调试器功能的同时从子进程报告自定义错误字符串
我有一个创建子进程的程序,并尝试按照以下方式处理任何错误消息:C# 如何在保留调试器功能的同时从子进程报告自定义错误字符串,c#,error-handling,C#,Error Handling,我有一个创建子进程的程序,并尝试按照以下方式处理任何错误消息: study.StartInfo.FileName = studyWorkingDir +"\\"+ clargParts[0]; study.StartInfo.Arguments = clargs; study.StartInfo.UseShellExecute = false; study.StartInfo.RedirectStandardError = true
study.StartInfo.FileName = studyWorkingDir +"\\"+ clargParts[0];
study.StartInfo.Arguments = clargs;
study.StartInfo.UseShellExecute = false;
study.StartInfo.RedirectStandardError = true;
study.ErrorDataReceived += (sender, args) =>
{
Process process = (Process)sender;
if (!process.HasExited)
{
MyErrorBroadcaster.BroadcastMessage("Instance error: " + args.Data.ToString());
process.kill();
}
};
study.Start(); // Start the Study!
study.PriorityClass = ProcessPriorityClass.BelowNormal;
study.BeginErrorReadLine();
子进程是一个应用程序(如下所示)。为了在上面的主进程中实际获得一个非空错误,我需要将整个子程序包装在一个try-catch中,这个try-catch会进行一个定制的Console.error.WriteLine()调用
问题是,子程序中的这个try-catch会阻止调试器在visualstudio中的实际错误位置停止,我认为这会使我和我的同事在开发过程中感到烦恼/产生问题。(看起来也很笨拙!)
是否有更好的方法让此子应用程序向主进程报告错误,而不影响正常的调试器操作?再次讨论此问题,问题是主进程一次只收到一行错误,第一行恰好是“”,然后它立即关闭进程(忽略以下错误行)。e.ToString().Replace(“\r\n”,“\t”)通过保证错误为一行,但有不必要的副作用,绕过了此问题 对我来说,更好的解决方案是:
study.StartInfo.UseShellExecute = false;
study.StartInfo.RedirectStandardError = true;
study.Start(); // Start the Study!
//This thread collects errors until the process ends, then reports them
(new Thread(() =>
{
//Acumulate errors, then send
String err = study.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(err))
MyErrorBroadcaster.BroadcastMessage("Instance Error", "\tInstance error: " + err);
})).Start();
此方法使用study.StandardError.ReadToEnd()。此命令是阻塞的,不适合我的目的,因此它位于lambda线程中(以便主程序可以继续!)不确定这是否是您想要的,但您可以在将详细信息写入控制台后重新抛出错误:
throw e;
study.StartInfo.UseShellExecute = false;
study.StartInfo.RedirectStandardError = true;
study.Start(); // Start the Study!
//This thread collects errors until the process ends, then reports them
(new Thread(() =>
{
//Acumulate errors, then send
String err = study.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(err))
MyErrorBroadcaster.BroadcastMessage("Instance Error", "\tInstance error: " + err);
})).Start();