Exceptions in multithreaded application.

前端 未结 10 1554
春和景丽
春和景丽 2021-02-15 00:02

I have heard from a very discerning person that an exception being thrown (and not caught) in a thread is being propagated to the parent thread. Is that true? I have tried some

10条回答
  •  名媛妹妹
    2021-02-15 00:16

    There is a very simple solution for the special case when the main thread waits for the completion of the other thread (see https://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx#Examples). It requires only a class exception variable.

    The modified code sample completed by an exception handler may look like this.

    using System;
    using System.Threading;
    
    class WaitOne
    {
        static AutoResetEvent autoEvent = new AutoResetEvent(false);
        static Exception SavedException = null;
    
        static void Main()
        {
            Console.WriteLine("Main starting.");
    
            ThreadPool.QueueUserWorkItem(
                new WaitCallback(WorkMethod), autoEvent);
    
            // Wait for work method to signal.
            autoEvent.WaitOne();
            if (SavedException != null)
            {
               // handle this exception as you want
            }
    
            Console.WriteLine("Work method signaled.\nMain ending.");
        }
    
        static void WorkMethod(object stateInfo) 
        {
            Console.WriteLine("Work starting.");
    
            // Simulate time spent working.
            try
            {
              Thread.Sleep(new Random().Next(100, 2000));
              throw new Exception("Test exception");
            }
            catch (Exception ex)
            {
                SavedException = ex;
            }            
    
            // Signal that work is finished.
            Console.WriteLine("Work ending.");
            ((AutoResetEvent)stateInfo).Set();
        }
    }
    

提交回复
热议问题