开发者

Catching unhandled exception of a thread

开发者 https://www.devze.com 2023-01-28 20:54 出处:网络
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 ?

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..

    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 PropertyOrFieldNotInitialized开发者_运维知识库Exception raised in my thread ? Would you have some best practice to catch exception from a thread in 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

 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 :

 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 !


Well, one way would be to use BackgroundWorker instead of a thread in your situation. 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.

EDIT:
You can also use an event of BackgroundWorker to report progress to your form, so you can update your progress bar properly ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消