Handling Exceptions from another thread
-
I am having some issue handling an exception thrown in another thread in my UI. My question is how can I handle exceptions from another thread without syncronized the threads in the UI. I would prefer to sync the threads in the class where the method is called. Any suggestions? Here is my code: Localized fields
Test t = new Test();
Method that throws the exception
public class Test
{
public void DoSomething()
{
throw new MyCustomException(this,EventArgs.Empty);
}
}The exception
public class MyCustomException : Exception
{
...
}This is in the UI. Not multi-threaded
void CallException() { try { t.DoSomething(); } catch(MyCustomException ex) { lblMessage.Text = "error"; } }
This is also in the UI. Multi-threaded
void CallExceptionASync() { Thread thrd; ThreadStart ts = (ThreadStart)delegate { t.DoSomething(); }; thrd = new Thread(ts); thrd.Start(); }
-
I am having some issue handling an exception thrown in another thread in my UI. My question is how can I handle exceptions from another thread without syncronized the threads in the UI. I would prefer to sync the threads in the class where the method is called. Any suggestions? Here is my code: Localized fields
Test t = new Test();
Method that throws the exception
public class Test
{
public void DoSomething()
{
throw new MyCustomException(this,EventArgs.Empty);
}
}The exception
public class MyCustomException : Exception
{
...
}This is in the UI. Not multi-threaded
void CallException() { try { t.DoSomething(); } catch(MyCustomException ex) { lblMessage.Text = "error"; } }
This is also in the UI. Multi-threaded
void CallExceptionASync() { Thread thrd; ThreadStart ts = (ThreadStart)delegate { t.DoSomething(); }; thrd = new Thread(ts); thrd.Start(); }
I have created a workaround but I am not satisfied with it. If anyone has a better suggestion please let me know. Here is the workaround:
void CallExceptionASync()
{
Thread thrd;
ThreadStart ts = (ThreadStart)delegate
{
try
{
t.DoSomething();
}
catch(MyCustomException ex)
{
this.lblMessage.Invoke((MethodInvokder)delegate()
{
this.lblMessage.Text = ex.Message;
});
}
}
} -
I have created a workaround but I am not satisfied with it. If anyone has a better suggestion please let me know. Here is the workaround:
void CallExceptionASync()
{
Thread thrd;
ThreadStart ts = (ThreadStart)delegate
{
try
{
t.DoSomething();
}
catch(MyCustomException ex)
{
this.lblMessage.Invoke((MethodInvokder)delegate()
{
this.lblMessage.Text = ex.Message;
});
}
}
}if the thread throws an exception, and the catch is to touch a GUI Control, then you need Control.Invoke, there is no way around that since that thread is not allowed to touch any Controls. BTW: A BackgroundWorker has a Completed event which does the invoking automatically, and its event argument holds the exception that may have occurred. :)