Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Handling exceptions in multithreaded dll

Status
Not open for further replies.

serializer

Programmer
May 15, 2006
143
SE
I have created a multithreaded dll which I am referencing in another project. I have created my own exceptions inheriting from Exception or ApplicationException object.

The problem I have is that try-catch does not work when it happens in another thread, below in the dll. How can I catch these errors, do I have to raise the errors to the main thread? How can I do that then? Thanks!
 
you have to catch the exception in the child thread. then pass this exception back to the main thread.

either create a seperate delegate/event for exceptions or include the exception as an argument/property for the completed delegate.

for example. include it with the completed event args
Code:
CompletedEventAgs : EventArgs
{
   object data;
   exception ex;
}
include the try/catch in the threaded process
Code:
try
{
  //do work
}
catch
{
   get exception
}
pass exception to completed event args (null if no error)
//call completed event
then in your parent thread check for an exception
Code:
void MyEventCompleted(object sender, CompletedEventArgs e)
{
   if(e.Exception != null)
   {
      //handle exception
   }
   else
   {
     //process completed
   }
}

or create a new object to handel exceptions.
Code:
Exception: EventArgs
{
   exception ex;
}
include the try/catch in the threaded process
Code:
try
{
  //do work
  //call completed event
}
catch
{
  //call exception event
}
then in your parent thread check for an exception
Code:
void MyEventCompleted(object sender, CompletedEventArgs e)
{
  //success
}

void MyEventErrored(object sender, ExceptionEventArgs e)
{
   //handle exception from child thread
}


Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Thanks, but I am not getting the exact behavior I want. What I want is to throw the exception to the application that is referencing my dll.

My preferred solution would be, if possible, to create a delegate and event like this:

public delegate void DelegateThrowException(Exception ex);
public static event DelegateThrowException EventThrowException;

Then, in my main thread I add some code to the constructor:

public void New()
{
EventThrowException += new DelegateThrowException(Form1_EventThrowException);
}

void Form1_EventThrowException(Exception ex)
{
throw ex;
}

Then I would create a static method which I could call from anywhere:


public static void RaiseException(Exception ex)
{
EventThrowException(ex);
}

What is wrong with this approach?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top