从另一个线程中捕获异常

Jer*_*emy 13 .net c# multithreading exception-handling exception

我有一个单独的线程运行的方法.该线程是从Windows应用程序中的表单创建和启动的.如果从线程内部抛出异常,将其传递回主应用程序的最佳方法是什么.现在,我将对主窗体的引用传递给线程,然后从线程调用该方法,并使该方法被主应用程序线程调用.是否有最好的练习方法,因为我现在对自己的表现不满意.

我的表格示例:

public class frmMyForm : System.Windows.Forms.Form
{
    /// <summary>
    /// Create a thread
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnTest_Click(object sender, EventArgs e)
    {
        try
        {
            //Create and start the thread
           ThreadExample pThreadExample = new ThreadExample(this);
           pThreadExample.Start();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName);
        }
    }

    /// <summary>
    /// Called from inside the thread 
    /// </summary>
    /// <param name="ex"></param>
    public void HandleError(Exception ex)
    {
        //Invoke a method in the GUI's main thread
        this.Invoke(new ThreadExample.delThreadSafeTriggerScript(HandleError), new Object[] { ex });
    }

    private void __HandleError(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的线程类的示例:

public class ThreadExample
{
    public delegate void delThreadSafeHandleException(System.Exception ex);

    private Thread thExample_m;

    frmMyForm pForm_m;
    private frmMyForm Form
    {
        get
        {
            return pForm_m;
        }
    }

    public ThreadExample(frmMyForm pForm)
    {
        pForm_m = pForm;

        thExample_m = new Thread(new ThreadStart(Main));
        thExample_m.Name = "Example Thread";
    }

    public void Start()
    {
        thExample_m.Start();
    }

    private void Main()
    {
        try
        {
            throw new Exception("Test");
        }
        catch (Exception ex)
        {
            Form.HandleException(ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 17

因此,您正在使用Invoke通过它的外观来回归到UI线程 - 这正是您需要做的.我个人使用Action <Exception>是为了简单起见,可能是BeginInvoke而不是Invoke,但基本上你做的是正确的.


jez*_*ell 5

请改用.NET框架中的BackgroundWorker类.这是在不同线程上执行UI工作的最佳实践.