bonk said:
The scenario is this: as soon as any excpetion occurs in one of the
threads the thread will be finished (there is one big try{}catch{}
inside the thread's callback. In case an exception occured the main
thread must be resonsible of handling the excpetion.
But what do you mean by "handle the exception"?
Typically, that phrase is used to describe the use of try/catch/finally to
provide a point at which the code can recover from the exception. But that
only will occur on the thread on which the exception occurred.
I suppose you could devise some way to duplicate the specifics of the
exception thrown, and then provide a bottleneck on the main thread where you
throw the duplicate. But I don't see the point in doing that, since all the
main thread will (presumably) do at that point is run some error-handling
code and continue normally. In that case, it makes more sense for the main
thread to simply run the error-handling code and be done with it, rather
than trying to emulate in the main thread an exception that happened on a
different thread.
[...]
Or maybe even better,
have the worker thread, upon catching a thrown exception, use Invoke or
BeginInvoke to run a delegate on the main thread, causing the main thread
to
process the error in whatever way you feel is appropriate.
This sounds like a good idea for my scenario. I now need to find out
how to run the delegate on the main thread an pass the exception
correctly.
IMHO, what you really want to know is how to extract the information that
you need from the exception, and pass *that* to the main thread. That said,
I suppose you could pass the exception itself. I'm just not sure what the
point of that would be, and it could tempt you into trying to rethrow the
exception on the main thread, which I think would be a mistake.
As Jon said, you can use Invoke or BeginInvoke to execute the delegate on
the main thread. You write that you have a console application, but that
doesn't preclude having a message pump. So one option is to go ahead and
run a message pump in your console application.
If that's not a suitable solution for you, then it seems to me you could
easily emulate the BeginInvoke behavior by creating a queue into which you
place your own "events" to be handled, and from which the main thread
retrieves for processing. Of course, by doing that you'd basically be
reinventing the wheel, and I'd think you'd be better off just putting a
message pump in your console application. But you could do it that way.
Pete