Where should my Try Catch block be when running a thread?

↘锁芯ラ 提交于 2020-01-13 20:42:07

问题


Take this thread:

Thread thread = new Thread(delegate()
            {
                //Code
            });

            thread.Start();

Should it be around the thread.Start(); or inside:

Thread thread = new Thread(delegate()
            {
                try
                {
                    //Code
                }
                catch (Exception)
                {
                    //Code
                }
            });

回答1:


it is completely different to put then inside or outside.

If you put them around the thread.Start() call, you can detect (according to this page: http://msdn.microsoft.com/en-us/library/system.threading.thread.start(v=vs.71).aspx)

  • ThreadStateException The thread has already been started.
  • SecurityException The caller does not have the appropriate SecurityPermission.
  • OutOfMemoryException There is not enough memory available to start this thread.
  • NullReferenceException This method was invoked on a thread reference that is a null reference (Nothing in Visual Basic).

If you put it inside, you will detect exception inside the code you will run in your thread. So any kind of exception you want.




回答2:


The exceptions pertaining the logic you have in the delegate should be handled inside the delegate.

thread.Start() itself can only throw ThreadStateException or OutOfMemoryException.




回答3:


Preventing silent thred termination

It explains to place the try catch inside of the delegate. It also talks about doing your finnally clean up if needed.




回答4:


If, as you mention above, the error is in the delegate code, then put the try-catch in there and log the exception. Alternatively, if you want that exception to be passed back to the original thread use an asynchronous delegate (calling EndInvoke will re-raise the exception to the calling thread or use Background worker and subscribe to RunWorkerCompleted event (this has error property in event args).



来源:https://stackoverflow.com/questions/6493138/where-should-my-try-catch-block-be-when-running-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!