繁体   English   中英

如何捕获 DataReceivedEventHandler 抛出的异常?

[英]How to catch Exception thrown by a DataReceivedEventHandler?

我怎么能捕捉到DataReceivedEventHandler抛出的Exception

这篇文章和我的一样,但对于异步方法而不是处理程序: 捕获异步无效方法抛出的异常

这是我的代码的过度简化版本:

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);
}

由于 Dortimer 的评论让我明白了,从事件处理程序抛出异常是一种不好的做法。 所以这是实现我想要做的事情的等效方法:

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM