I was recently asked by someone to help debug a ThreadAbortException. Here's the simplified code ...
public class MyThread { public void Run() { while( true ) { try { lock( LockObj ) { Monitor.Wait( LockObj ); } } catch( Exception ex ) { Console.WriteLine( ex.Message ); } } } }
public void ThreadRunTest() { MyThread thread = new MyThread(); ThreadStart ts = new ThreadStart( thread.Run ); Thread t = new Thread( ts ); t.Start(); }
Running this results in the following exception message:
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
As the exception suggests, it seems MyThread is being aborted during execution. Running this sample code as a test case, you can reproduce the problem. Notice ThreadRunTest starts the thread, but does not wait for its completion. So when ThreadRunTest ends, all thread are forced to abort resulting in ThreadAbortException. So this should be a simple fix ...
public void ThreadRunTest() { MyThread thread = new MyThread(); ThreadStart ts = new ThreadStart( thread.Run ); Thread t = new Thread( ts ); t.Start(); t.Join(); }
Here are MSDN page on ThreadAbortException Class and Thread.Join Method
UPDATE: If you are using ThreadPool.QueueUserWorkItem, consider doing the following:
class MyClass { static void Main() { AutoResetEvent autoEvent = new AutoResetEvent( false ); ThreadPool.QueueUserWorkItem( new WaitCallback( WorkMethod ), autoEvent ); autoEvent.WaitOne(); // Wait for background thread to end }
static void WorkMethod( object stateInfo ) { Console.WriteLine( "executing WorkMethod" ); ( (AutoResetEvent)stateInfo ).Set(); // Signal that this thread is finished } }


0 comments:
Post a Comment