2

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
                }
            });
2
  • 1
    That would depend on if you are trying to trap errors in the line thread.Start() or in the body of the method it runs. Commented Jun 27, 2011 at 13:02
  • @spender: I get errors inside the body. The methods in there has try catch blocks as well, and then nothing happens when the errors are caught. It crashes my entire app. So would it be best to have a try inside the body and around the .Start()? Commented Jun 27, 2011 at 13:08

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.