Exceptions in multithreaded application.

前端 未结 10 1516
春和景丽
春和景丽 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:18

    Here is one way of catching it and handling it in a safe way:

    BackgroundWorker bg = new BackgroundWorker();
    object o;
    bg.DoWork += (c1,c2) =>
    {         
            Thread.Sleep(2000);        
            throw new IndexOutOfRangeException();
    };
    
    bg.RunWorkerCompleted += (c3,c4) => 
    {
    
     if (((RunWorkerCompletedEventArgs)e).Error != null)
        {
            MessageBox.Show(((RunWorkerCompletedEventArgs)e).Error.Message);
        }
    };
    

提交回复
热议问题