What happens when an exception is thrown from within a new thread of execution?

How do I catch it? Must it be within the same thread?

Also, what is the proper way to update a control residing on a form, from within a new thread? I think it would be using a delegate, but I'm extremely new to C#.

Recommended Answers

All 4 Replies

Depends on how you invoke the thread, but normally yes. It isn't passed on to the main thread but it can bring your whole system down.

And yes, using a delegate is the way to go for cross-thread control access.

I believe that when an exception is thrown from another thread started using Thread.Start(), it terminates the thread, but when you are not debugging it does not give an error message to the user, just shuts down quietly. I'm not too sure about that though.

What I am sure about, however:
If you started the thread with the BeginInvoke() method of a delegate, the exception can only be obtained by calling EndInvoke() on the delegate instance if the actual method did not handle the exception. In that case, EndInvoke() throws the same exception that terminated the thread pool thread. If you do not call EndInvoke(), unhandled exceptions are lost. This is also true for the System.Timers.Timer class, which also uses threads from the thread pool.

I believe that when an exception is thrown from another thread started using Thread.Start(), it terminates the thread, but when you are not debugging it does not give an error message to the user, just shuts down quietly. I'm not too sure about that though.

When an unhandled exception is thrown on a thread it can do anything from shutting down quietly, to crashing the whole system, to leaving your system in an unstable state which might cause database/file corruption. You should always put some form of exception handling around the main process of your thread.

Yes, thanks for the Exception info, and using delegates to call a function residing on the same thread the control was created is one way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.