none
Thread.Abort and App crash RRS feed

  • Question

  • Hi, all

    I found something wierd with my program

    using System;
    using System.Data.SqlTypes;
    using System.Threading;
    namespace TestCrash
    {
      class Program
      {
        static void Main(string[] args)
        {
          /*Console.WriteLine(typeof(SqlInt32));*/
          var h = new Holder();
          h.Test();
          Console.WriteLine("TestHolder");
          Console.ReadLine();
        }
      }
      public class Holder
      {
          private Thread t;
          private void Work()
          {
              Thread.Sleep(Timeout.Infinite);
          }
          ~Holder()
          {
              t.Abort();
          }
          public void Test()
          {
              t = new Thread(new ThreadStart(Work));
              t.IsBackground = true;
              t.Start();
          }
      }
    }

    This program terminates normally, however, if I uncomment the fisrt code line in Main which prints type of 'System.Data.SqlTypes.SqlInt32', the program will crash when exit, and the windows event tells me that 'Access Violation' (0xc0000005)

    Faulting application name: TestCrash.exe, version: 1.0.0.0, time stamp: 0x52b0189a
    Faulting module name: ntdll.dll, version: 6.1.7600.16385, time stamp: 0x4a5be02b
    Exception code: 0xc0000005
    Fault offset: 0x00000000000159ad
    Faulting process id: 0x1f20
    Faulting application start time: 0x01cefb129f0bf5e8
    Faulting application path: C:\yuanf\Flx\Source\TestCrash\bin\Debug\TestCrash.exe
    Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
    Report Id: ddf78d96-6705-11e3-bafd-005056b80090

    I found it has something to do with the thread abort, but can anyone explain why abort the 'Work' thread in the finalizer will cause the crash, while in other threads this will work well?

    After some experiment, I found actually, instead of printing 'System.Data.SqlTypes.SqlInt32', any code that can introduce loading of the System.Data.dll will make this program terminate abnormally. How does it matters?

    To be noted, according to my test, the crash happens only on .NET 4.0 (my test machines are windows 2008R2, and win 7, both with .NET framework of version 4.0.30319)

    Thank you in advance!

    Wednesday, December 18, 2013 2:53 AM

Answers

  • I don't have a Win2008 machine handy to test your code but even if there really is a bug in .NET your code is basically asking for it.

    Using Thread.Abort is not a good idea to begin with (even though it's unlikely to be itself responsible for such a crash), calling Abort from a finalizer is just weird. The Thread object is finalizable too,  what will happen if the thread gets finalized first and you end up aborting a finalized thread I don't know. I don't think it should crash like that but if does don't be too surprised.

    Wednesday, December 18, 2013 12:30 PM
    Moderator

All replies