我如何捕捉Exception
抛出的DataReceivedEventHandler
?
此帖子与我的相同,但适用于异步方法而非处理程序:Catch an exception thrown by an async void method
这是我的代码的过度简化版本:
public static void Main()
{
try
{
using (Process process = CreateProcess())
{
process.Start();
process.BeginErrorReadLine();
process.WaitForExit();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message); // never goes here
}
}
private static Process CreateProcess()
{
Process process = new Process();
process.ErrorDataReceived += ActionOnErrorDataReceived;
return process;
}
private static void ActionOnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
throw new Exception(e?.Data);
}
答案 0 :(得分:0)
由于Dortimer的comment使我理解了,所以从事件处理程序中引发异常是一种不好的做法。因此,这是实现我正在尝试实现的等效方法:
bool error = false;
string errorMsg = String.Empty;
public static void Main()
{
try
{
using (Process process = CreateProcess())
{
process.Start();
process.BeginErrorReadLine();
process.WaitForExit();
if (error)
{
throw new Exception(errorMsg);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static Process CreateProcess()
{
Process process = new Process();
process.ErrorDataReceived += ActionOnErrorDataReceived;
return process;
}
private static void ActionOnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
error = true;
errorMsg = e?.Data;
Process p = (sender as Process);
if (p != null && p.HasExited == false)
{
p.Kill();
}
}