[Mono-list] Problem with Thread.Abort()

peter apvx95@dsl.pipex.com
Fri, 08 Apr 2005 18:31:57 +0100


In my continuing journey through /"Mono: a developers' handbook"/, in 
the section in chapter 3 on threads, an example program calls 
Thread.Abort() to kill the thread previously created, and exit the 
program.  The code is as follows:

> // 03-keyfunc/07-threading/UseThreadPool.cs
> using System;
> using System.IO;
> using System.Threading;
>
> public class UseThreadPool {
>     private static Thread thread;
>
>     public static void Main(string[] args) {
>         WaitCallback callback = new WaitCallback(Callback);
>         Console.WriteLine("Calling QueueUserWorkItem()...");
>         ThreadPool.QueueUserWorkItem(callback);
>         
>         Console.WriteLine("Hit return to exit.");
>         Console.In.ReadLine();
>         
>         thread.Abort();
>         
>         Console.WriteLine("Done.");
>     }
>     
>     private static void Callback(object state) {
>         thread = Thread.CurrentThread;
>         
>         Console.WriteLine("Started thread {0}", thread.GetHashCode());
>         
>         Random random = new Random();
>         for (int counter = 0; true; counter++) {
>             try {
>                 Thread.Sleep(random.Next(10000));
>             } catch (ThreadAbortException) {
>                 Console.WriteLine("Aborting thread");
>                 // Environment.Exit(0);
>             }
>             Console.WriteLine("{0}: {1}", counter, DateTime.Now);
>         }
>     }
> }
>                

Obviously the expectation is that the call to Abort() will cause a 
ThreadAbortException to be raised in the delegate method.  However this 
doesn't happen for me.  Instead, the Main() method exits, but the thread 
continues:

> peter@linux:~/monoDevelopersNotebook/03-keyfunc/07-threading> mono 
> UseThreadPool.exe
> Calling QueueUserWorkItem()...
> Hit return to exit.
> Started thread -1392333056
> 0: 08/04/2005 18:27:10
> 1: 08/04/2005 18:27:10
>
> Done.
> 2: 08/04/2005 18:27:17
> 3: 08/04/2005 18:27:18
>
> peter@linux:~/monoDevelopersNotebook/03-keyfunc/07-threading>

[Ctl]-C will stop the program, as you'd expect.

Is this a problem with me (likely), a problem with the book (possible), 
a problem with the Mono threading implementation (unlikely), or 
something I'm not bright enough to spot?

It's not the end of the world; but an explanation would be welcomed.  
Just to put my mind at rest.

Thanks

Peter