Solved

vb.net exception handling with multiple threads

Posted on 2011-09-14
5
399 Views
Last Modified: 2012-05-12
Hi,

Was looking on internet about this but didn't see anything clear about how you should handle exceptions in multiple threads. I have an application which creates three threads which run on the same subroutine (lets call it mySub). These are created on a main thread inside a try catch block which has a finally section which cleans up any references to objects that need to be disposed of.

I'm not that familiar with threads but I know that a thread basically ends when exit sub is called or when the code completes. So, is it the case that if an error occurs in the sub on one of the three newly created threads, then I catch that error in a try catch block in mySub, and then I should throw an exception back up to the main thread? Should I use thread.abort in this try catch block in order to throw a ThreadAbortException? Well presumably I will want to throw the exception that occurred on the thread so that the main thread can read it? maybe something like the below? (I could of course be more specific with the type of exception or create my own exception type)

Then when the exception comes to the calling thread... should I terminate the other two threads at that point? Again a thread.abort? I've heard that's pretty risky... maybe it's ok if you use a begincriticalregion area to make sure it aborts in a safe place?

Thanks, Aiden


Try   
   Dim paramTS As New ParameterizedThreadStart(AddressOf mySub)
   Dim t1 As Thread = New Thread(paramTS)
   t1.Start(myParameters)
Catch ex As Exception
   MsgBox("Error occurred: " & ex.ToString)
Finally
   CleanUp()
End Try

Sub mySub
   Try
      'Do work
   Catch ex As Exception
       Throw New Exception("Exception occurred")
   End Try
End Sub

Open in new window

0
Comment
Question by:AidenA
  • 3
  • 2
5 Comments
 
LVL 16

Expert Comment

by:HooKooDooKu
ID: 36540730
Once a thread starts, it has a life of its own independant of what ever subroutine started it.  It will have it's own exception stack with no way to throw an exception back to the subroutine that created the thread.  After all, think about it.  In most cases, once a subroutine has started a thread, it continues doing its own processing, most likely leaving the try-catch block that started the thread, and modifying its own exception stack as it executes through other try-catch blocks.

So if there isn't a top-level try-catch block within the thread (i.e. a try-catch block for the thread's main subroutine), an unhandled exception will terminate the thread just like an unhandled exception will terminate a single threaded program.

And actually, if the main program thread terminates because of an unhandled exception, the child threads will still continue executing.  You should be able to toss together some simple test code and force some exceptions a display debug code or message boxes to prove this.
0
 

Author Comment

by:AidenA
ID: 36542586
Hi thanks for that...

But I'm sure there must be a way of doing it? I can't believe that there is no way of knowing that an exception happened on one of your threads and finding out what that is.
0
 

Author Comment

by:AidenA
ID: 36542604
or at least, there must be some way that if an error happens in one of your threads, you can log the error as normal... and then stop all other threads and clean up any references... how do you do that?

0
 
LVL 16

Accepted Solution

by:
HooKooDooKu earned 500 total points
ID: 36599416
Well when it comes to thread stopping, the only way to cleaning stop threads is to set up some sort of signaling method.  Some simple examples include having global or class level variables that both threads can access.  Then one thread can flag the other to tell it to stop, or to inform another thread that the 1st thread completed.

So in the case of exception handling, you just place an exception at the top level function of the thread, and include setting some flags to indicate what has happened.

The only other thing you've got to work with is that every thread can have an exit value.  Your top-level exception handling for the thread can then return an "error" value when the thread terminates.  If you have a copy of a threads handle, their is an API function call that allows you to determine if the thread is still running or what it's exit code was.  However, to properly utilize this sort of functionality, you have to be able to start a thread in suspended mode, create a duplicate handle, then resume the suspended thread.  (If you attempt to use the thread's handle itself, there is always the possibility that the thread has finished execution and the handle no longer valid when you try to use it).
0
 

Author Comment

by:AidenA
ID: 36599661
woah... complicated then!

I'm surprised the framework doesn't have some way of easily handling such a situation. But from what I've been reading, it does seem to get complicated as soon as you want to communicate between threads (as I saw when trying to set the progress bar on the UI from a new thread - needed delegates and whatnot)...

thanks for the info anyway, I will keep in mind
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now