Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    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 ? 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 !

like image 350
KitAndKat Avatar asked Dec 06 '10 10:12

KitAndKat


1 Answers

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

like image 102
Thorsten Dittmar Avatar answered Oct 27 '22 05:10

Thorsten Dittmar