如何在主进程中处理BackgroundWorker的异常?

时间:2013-04-18 13:20:44

标签: c# winforms exception backgroundworker

我想处理我的Progress类中的所有未处理的异常,我在其中编写了一些错误记录代码:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new LoginPoint());
        }
        catch (Exception myException)
        {
            //log the unhandled exceptions.                
        }
    }
}

BackgroundWorker中的例外情况未得到正确处理:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    throw new Exception("TEST EXCEPTION!");
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        throw new Exception("I GOT THE EXCEPTION");
    }
}

我希望在我的Progress类中处理异常“I GOT ...”,但是当我运行(而不是调试)应用程序时,会出现系统的异常对话框。 / p>

3 个答案:

答案 0 :(得分:2)

您可以使用AppDomain.UnhandledException事件

答案 1 :(得分:1)

program.cs中的

执行此操作:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
    Application.Run(new Form1());
}

static void AppDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
    MessageBox.Show(((Exception)e.ExceptionObject).Message, "AppDomain.UnhandledException");
    Environment.Exit(-1);
}

你的表单代码应该可以使用它,你应该在运行模式下获得AppDomain.UnhandledException MessageBox(ctrl + F5)

答案 2 :(得分:0)

我的方法可能是事件处理程序。你面临的问题是跨线程的沟通,这是一个臭名昭着的无赖!您应该研究线程并调用以了解更多相关信息。但是,您可以使用事件和事件处理程序在工作线程和主线程之间安全地进行通信。这是一个简短的例子:

public delegate void ExceptionHandler(Exception ex);

public class Worker : BackgroundWorker
{
    ExceptionHandler Handler { get; set; }

    public Worker(ExceptionHandler handler)
    {
        Handler = handler;
    }

    protected override void OnDoWork(DoWorkEventArgs e)
    {
        for (var i = 0; i < (int)e.Argument; i++)
        {
            if (i%2 != 0) continue;

            try
            {
                throw new ArgumentException(String.Format("{0}:{1}", i, "TEST EXCEPTION"));
            }
            catch (Exception ex)
            {
                if (this.Handler != null)
                    Handler.Invoke(ex);
            }
        }
    }
}

class Program
{
    public static void HandleException(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    static event ExceptionHandler Handler;

    static void Main(string[] args)
    {
        Handler = new ExceptionHandler(HandleException);
        var worker = new Worker(Handler);
        worker.RunWorkerAsync(100);

        Console.ReadLine();
    }
}

控制台窗口中的预期输出为:

0:TEST EXCEPTION
2:TEST EXCEPTION
4:TEST EXCEPTION
6:TEST EXCEPTION
etc etc

希望证明有用,即使它不是您正在寻找的答案,希望它会以某种方式帮助您。