Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Exceptions From Threads

Exceptions From Threads

Scheduled Pinned Locked Moved C#
regexquestion
3 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    JohnLBevan
    wrote on last edited by
    #1

    Hi Folks, on to the second of tonight's threading queries... Does anyone know of a suitable pattern for exception handling where threads are involved, or if there's a special kind of exception which can bubble up into the parent thread?

    class Program
    {
        static void Main(string\[\] args)
        {
            try
            {
                Demo demo = new Demo();
                Timer timer1 = new Timer();
                timer1.Interval = 3000;
                timer1.Elapsed += new ElapsedEventHandler(demo.Run);
                timer1.Enabled = true;
            }
            catch (Exception e)
            {
                //I want this to catch the IllTellMyDadThreadException exception
                Console.WriteLine("You should write an exception handler");
            }
            Console.ReadKey();
        }
    }
    
    class Demo
    {
        public void Run(object source, ElapsedEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(2000);
                DoSomething();
                System.Threading.Thread.Sleep(2000);
            }
            catch (Exception e)
            {
                throw new IllTellMyDadThreadException(e);
            }
        }
        private void DoSomething()
        {
            throw new Exception("aaaugh");
        }
    }
    

    Thanks once again for any suggestions, JB

    L 1 Reply Last reply
    0
    • J JohnLBevan

      Hi Folks, on to the second of tonight's threading queries... Does anyone know of a suitable pattern for exception handling where threads are involved, or if there's a special kind of exception which can bubble up into the parent thread?

      class Program
      {
          static void Main(string\[\] args)
          {
              try
              {
                  Demo demo = new Demo();
                  Timer timer1 = new Timer();
                  timer1.Interval = 3000;
                  timer1.Elapsed += new ElapsedEventHandler(demo.Run);
                  timer1.Enabled = true;
              }
              catch (Exception e)
              {
                  //I want this to catch the IllTellMyDadThreadException exception
                  Console.WriteLine("You should write an exception handler");
              }
              Console.ReadKey();
          }
      }
      
      class Demo
      {
          public void Run(object source, ElapsedEventArgs e)
          {
              try
              {
                  System.Threading.Thread.Sleep(2000);
                  DoSomething();
                  System.Threading.Thread.Sleep(2000);
              }
              catch (Exception e)
              {
                  throw new IllTellMyDadThreadException(e);
              }
          }
          private void DoSomething()
          {
              throw new Exception("aaaugh");
          }
      }
      

      Thanks once again for any suggestions, JB

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      So what you have created here is: - a main thread launching a repetitive timer; - a timer executing "something" on another thread (which happens to be an arbitrary ThreadPool thread); - as your Run() method takes longer than your timer's interval, two ThreadPool threads are likely to be executing the Run() method in an overlapping way, i.e. a second will start before the first has finished. No, whatever goes wrong in Run() stays in there. The threadpool thread will survive but not report anything. Unless (I'm not sure, haven't done this for a while) you set a handler to Application.ThreadException; but then that handler will possibly catch a lot, and your app will in general have a hard time to somehow recover from whatever went wrong. Here is an alternative that may or may not fit your needs: have a look at BackGroundWorker; this basically is a thread that executes your work; when everything is done, it fires its RunWorkerCompleted event, which (1) runs on the main thread (assuming you created the BGW on the main thread), so you can touch GUI Controls freely from there; and (2) has an Error parameter that holds any uncaught exception that may have occured in (and terminated execution of) the DoWork handler. This way, the exception is there, when you want it, and close to what has caused it. :)

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


      I only read formatted code with indentation, so please use PRE tags for code snippets.


      I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


      J 1 Reply Last reply
      0
      • L Luc Pattyn

        So what you have created here is: - a main thread launching a repetitive timer; - a timer executing "something" on another thread (which happens to be an arbitrary ThreadPool thread); - as your Run() method takes longer than your timer's interval, two ThreadPool threads are likely to be executing the Run() method in an overlapping way, i.e. a second will start before the first has finished. No, whatever goes wrong in Run() stays in there. The threadpool thread will survive but not report anything. Unless (I'm not sure, haven't done this for a while) you set a handler to Application.ThreadException; but then that handler will possibly catch a lot, and your app will in general have a hard time to somehow recover from whatever went wrong. Here is an alternative that may or may not fit your needs: have a look at BackGroundWorker; this basically is a thread that executes your work; when everything is done, it fires its RunWorkerCompleted event, which (1) runs on the main thread (assuming you created the BGW on the main thread), so you can touch GUI Controls freely from there; and (2) has an Error parameter that holds any uncaught exception that may have occured in (and terminated execution of) the DoWork handler. This way, the exception is there, when you want it, and close to what has caused it. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


        I only read formatted code with indentation, so please use PRE tags for code snippets.


        I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


        J Offline
        J Offline
        JohnLBevan
        wrote on last edited by
        #3

        Thanks for the info about the BackgroundWorker; I hadn't used that before. I had a play, and that works well for running threads and catching exceptions, but as I needed to trigger it from a timer, the issue of bubbling exceptions up past the timer remained. When I tried using the worker's completed event, to retrigger it, this caused a new asynchronous thread to be created, which worried me about the potential for memory leaks and stack overflows; these may not be an issue, but my knowledge isn't good enough to feel comfortable with this yet. However, I realised that I'd missed an obvious solution. The actual issue I was trying to solve is this: I have a windows service, which starts a number of threads to poll different resources at various intervals (e.g. one thread monitors a folder on the file system every 30 seconds, another queries a database every hour). These threads are to run in parallel, and also run the handling code for where results are found (ceasing to poll whilst the handler code runs to avoid overloading it). Should an exception occurs in one of these threads, I wanted to ensure that it was reported to the eventlog, so put a try catch around the service call, hoping for it to catch all exceptions. My solution was to simply change from using a top level exception handler to using a singleton exception handler available to all threads. Each thread then had the standard exception bucket around all of its contents, allowing exceptions to be reported correctly. As I say, this is a solution to a different problem to the one I initially posted, but hopefully this'll help others with similar issues. Thanks again to Luc for all your assistance. JB

        1 Reply Last reply
        0
        Reply
        • Reply as topic
        Log in to reply
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes


        • Login

        • Don't have an account? Register

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • World
        • Users
        • Groups