简体   繁体   English

捕获线程的未处理异常

[英]Catching unhandled exception of a thread

Does one of you has an idea of how to catch in the main thread of an application an exception thrown in a particular thread ? 你们其中一个人是否知道如何在应用程序的主线程中捕获特定线程中抛出的异常?

For example, I have a very simple thread doing some basic stuff : 例如,我有一个非常简单的线程做一些基本的东西:

 try
        {
            Thread t = new Thread(new ThreadStart(Cache.initialize));
            t.Start();
            t.Name = "loading";
            while (t.IsAlive)
            {
                progressBar1.PerformStep();
             }
        }

        catch (PropertyOrFieldNotInitializedException ex)
        {
            Console.WriteLine(ex.StackTrace);
            MessageBox.Show("L'application ne peut se connecter au serveur, vérifiez votre connexion");
        }

the problem is that this catch is useless, because the exception won't be retrieved in the main stack.. 问题是这个catch没用,因为在主栈中不会检索异常。

    public static void initialize()
        {
            try
            {
                ctxMdv = new ClientContext(Configuration.getInstance().UrlMdv);
                ...                
            }

            catch (PropertyOrFieldNotInitializedException e) //si le serveur n'est pas démarré
{
                throw ;
            }

here everything stops at the "throw" and nothing is handled, even if in the main stack I tried to catch it displaying a message box. 这里的一切都停在“抛出”并且没有任何处理,即使在主堆栈中我试图抓住它显示一个消息框。 So how could I catch this PropertyOrFieldNotInitializedException raised in my thread ? 那我怎么能抓住我的线程中引发的PropertyOrFieldNotInitializedException呢? Would you have some best practice to catch exception from a thread in c# ? 您是否有一些最佳实践来从c#中的线程中捕获异常?

Thank you very much ! 非常感谢你 !

PS : Okay thanks to the answer given by Thorsten Dittmar below, I could make it work like that : here is the main thread PS:好的,多亏了Thorsten Dittmar给出的答案,我可以让它像那样工作:这里是主线程

 BackgroundWorker bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        bw.RunWorkerAsync();

here is my dowork : 这是我的笨蛋:

private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        Cache.initialize(); // the thread job
    }

here is mi completed event, that happens even if an exception is raised : 这是mi完成的事件,即使引发异常也会发生:

 private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      if (!(e.Error == null))

            if (e.Error is WebException)
                Console.WriteLine(e.Error.StackTrace);
            MessageBox.Show("L'application ne peut se connecter au serveur, vérifiez votre connexion");

         this.Dispose();
         Application.Exit();
    }

And I'm planning to handle the ProgressChanged delegate to correct the progression bar... ;) thank you ! 而且我打算处理ProgressChanged代表以纠正进度条...;)谢谢!

Well, one way would be to use BackgroundWorker instead of a thread in your situation. 好吧,一种方法是在您的情况下使用BackgroundWorker而不是线程。 You don't need a try block there, as errors will be automatically caught and passed to the handler you assign when the worker ends. 您不需要在那里使用try块,因为错误将被自动捕获并传递给您在工作人员结束时分配的处理程序。

EDIT: 编辑:
You can also use an event of BackgroundWorker to report progress to your form, so you can update your progress bar properly ;-) 您还可以使用BackgroundWorker事件向表单报告进度,以便您可以正确更新进度条;-)

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

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