rodniko

override public void RunThread()

{

try

{

while (true)

{

Thread.Sleep(1);

Connect();

}

}

catch (Exception Err)

{

throw new Exception(Err.Message); // Error : "Exception was unhandled"

}

i create the thread like that :

this.SearchThread = new Thread(new ThreadStart(this.RunThread));

this.SearchThread.IsBackground = true;

this.SearchThread.Start();

I get an exception from Connect() function.

when i try to throw the exception to the class that created the thread i get an "Exception was unhandled". i understand that although the thread is created in the owner class ,he is not in the same thread as the owner class and that's why ( i think) i can't throw the exception to the owner class.

How do i handle a thread exception ( notify the class that created him that there was an exception )

i tried to call a function of the owner class by delegate from inside the thread but it is still a different thread than the owner class thread and i still get the same exception from the function.



Re: Visual C# General Handling Exceptions from inside threads?

DQM

have you implemented the ThreadExceptionHandler delegate Here is a link to a post with a code sample - http://blogs.msdn.com/winformsue/archive/2006/02/08/527941.aspx.

P.S. Couldn't use the link feature as my FireFox crashes when pasting the URL....





Re: Visual C# General Handling Exceptions from inside threads?

rodniko

Thanks , i went over the msdn sample you sent me.

it is so complicated :) , but eventually i understood it.

the link explains how to catch unhandled thread Exceptions in the Application object but not catching thread exceptions in simple modules (class libraries) because the Application object has a built-in ThreadException variable which my module doesn't and furthur more the exmple sais :

"// NOTE: This exception cannot be kept from terminating the application - it can only
// log the event, and inform the user about it."

i don't want my application to terminate eventually , i just want to catch the worker thread exception in the module that created the thread.

i need a more simple example and also an example that can be implemented not only in Application object but in class libraries too.

anyone

( i had the same problem with using Controls from worker threads because the control is in a different thread than the worker thread i created ( Cross-thread exception), i solved it by "invoke" , Don't exceptions from one thread be passed to another thread in the same way )





Re: Visual C# General Handling Exceptions from inside threads?

Matthew Watson

There is a fundamental difference between User Interface threads and Worker threads:

A User Interface thread has a message loop, but a Worker thread does not. The Invoke() mechanism used to transition between a Worker thread and a User Interface thread uses window messages to communicate between them. This can only work because the User Interface thread processes window messages. A worker thread does not process messages, therefore this mechansim cannot be used.

You cannot "call back" into a particular worker thread in response to an exception in another thread without a using message loop.

So, how to communicate between two worker threads, one of which instantiates the other (Let us call the instantiator the "Primary" worker, and the other thread the "Secondary" worker.)

The easiest way is to use a Delegate to start the secondary thread, rather than a Thread object. If you use a Delegate, the secondary thread will "remember" any exception that occured, and will allow the primary thread to recieve that exception at its leisure.

However, at some point in your code, SOMETHING will have to wait for the secondary thread to complete. In the absence of any user interface threads, the primary thread will have to wait.



private void button1Click(object sender, EventArgs e)
{
WorkerDelegate worker = new WorkerDelegate(Worker);
IAsyncResult asyncResult = worker.BeginInvoke(null, null);

Thread.Sleep(2000); // Simulate doing some work.

while (!asyncResult.IsCompleted) // Wait for thread to complete.
Thread.Sleep(100);

try
{
worker.EndInvoke(asyncResult);
}

catch (Exception ex)
{
MessageBox.Show("Exception: " + ex.Message);

// Handle exceptions here.
}
}

delegate void WorkerDelegate();

private void Worker()
{
Debug.WriteLine("Entered worker");
Thread.Sleep(5000);
Debug.WriteLine("Leaving worker");
throw new InvalidOperationException("Bang bang, you're dead!");
}







Re: Visual C# General Handling Exceptions from inside threads?

rodniko

Thank you Matthew , i learned alot from your thread :)

but this is still not the solution i'm looking for because i can't afford my dll (that creates the 'secondary' thread) to wait.

his other methods are used while the 'secondary' thread runs.

i need a solution that enables me to catch a worker thread ('secondary' thread) exception in my dll ('primary' thread) without it waiting for the worker thread to be over.

i continue to research this matter , i found an object called BackgroundWorker , i read about it as we speak.....

This object has a way of handling worker thread exceptions.....

what do you peaple think about it

any other ways to solve this mystery will be accepted gladly :)





Re: Visual C# General Handling Exceptions from inside threads?

Matthew Watson

Using a BackgroundWorker requires a Control, so you can't use that I'm afraid. (If you could, then your first method would have worked too.)

If you use BeginInvoke() with a delegate, you don't have to wait for the thread to finish - you could expose a method that checked to see if the thread had finished (and returned its status).

But your only choices are for your primary worker thread to poll or wait. There is no way for a thread to "interrupt" another one in the way that you want. (Threads with a message loop are of course doing polling in the background, when their message loop checks for new messages.)

There should be better ways to do this - how do you want the client code to be able to call into your class library Let's start with the desired interface, and then work out how to do it! I think you're getting bogged down in implementation details that aren't actually necessary...






Re: Visual C# General Handling Exceptions from inside threads?

rodniko

thanks matthew,

ok , i got it now , i understand that i can't send exception from a 'secondary' thread to the dll that creates him without the dll wait or poll. so i'll settle for throwing the exception to the UI , that way i'll save the poll or wait of the dll and i'll use the UI message loop to poll for me ( if i got you right....:))

so what i though in doing next is send the exception from the worker thread to the application, but how do i do that without going through my dll first :

My Application uses the dll that creates the worker thread :

TCPComm = new TCPIPComm(); // TCPComm is the dll

TCPComm.Connect(); // Connect() creates a worker thread inside TCPComm that raise an exception

To be more specific i have a form that creates a TCPIP dll that i created.

This dll calls Connect() function that i wrote. This function creates a worker thread thats waits for a connection. that's all ! . easy right not! because if i have an exception inside the thread i can't notify the TCPIP dll without him wait or poll (which i can't afford to do ),so my only option is to notify the UI (Form).

i need to notify from inside the worker thread of an exception to the application.

The example DQM gave me is good ,but it's for Forms that themselves create the thread. It doesn't talk about a form using a dll that creates a thread.

How do i make the UI to get the exception event from the thread inside the dll





Re: Visual C# General Handling Exceptions from inside threads?

Matthew Watson

You should add an 'event' to your TCPComm class, through which the worker thread can signal a failure (or completion).

Let's call the event "CommunicationComplete".

Then your form will:

(1) Create an instance of TCPComm called, say, tcpComm.
(2) Subscribe to the event using tcpComm.CommunicationComplete += ... the event handler

Inside the handler for the event, you will need to check "this.InvokeRequired" to see if you need to call "this.Invoke()" to call back on the UI thread, or if you are already on the UI thread:

Inside the TCPComm class, your code for firing the event will be something like:

private void OnThreadTerminated()
{
    EventHandler<SomethingHappenedEventArgs> handler = SomethingHappened;

    if (handler != null)
    {
        handler(this, new SomethingHappenedEventArgs();  // Call the handler.
    }
}

Have you ever worked with events If not, you'll have to read up on them a bit... ;)




Re: Visual C# General Handling Exceptions from inside threads?

rodniko

got it , reading it , implementing it.

Thanks!





Re: Visual C# General Handling Exceptions from inside threads?

rodniko

I implemented the event handling. it works great!.

when i have an exception in the thread (which inside the TcpComm dll ) i call the event which operate a function in the Form.

but then i tried something else , i passed the event handling code to the dll itself ( to make my code more encapsulated ) . now i call a function of the dll from the thread ,not the Form function ,and it still works!. How come

events work with the help of the message loop right dlls don't have message loop, so i expected that the event wouldn't be able to operate the dll function from inside the thread.....

does this means my dll has a message loop too





Re: Visual C# General Handling Exceptions from inside threads?

Matthew Watson

Events don't use the message loop - but Control.Invoke() does.