Is using Thread.Abort() and handling ThreadAbortException in .NET safe practice?

前端 未结 7 982
执念已碎
执念已碎 2020-12-10 06:26

I need to develop a multithreaded Azure worker role in C# - create multiple threads, feed requests to them, each request might require some very long time to process (not my

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 07:16

    One example where it's problematic to abort a thread.

    using(var disposable=new ClassThatShouldBeDisposed())
    {
       ...
    }
    

    Now the Thread abortion happes after the constructor of the class has finished but before the assignment to the local variable. So it won't be disposed. Eventually the finalizer will run, but that can be much later.

    Deterministic disposing and thread abortion don't work well together. The only way I know to get safe disposing when using thread abortion is putting all the critical code inside a finally clause.

    try
    {//Empty try block
    }
    finally
    {
      //put all your code in the finally clause to fool thread abortion
      using(var disposable=new ClassThatShouldBeDisposed())
      {
      ...
      }
    }
    

    This works because thread abortion allows finally code to execute. Of course this implies that the thread abortion will simply not work until the code leaves the finally block.

    One way to get your code to work correctly with thread abortion is using the following instead of the using statement. Unfortunately it's very ugly.

    ClassThatShouldBeDisposed disposable=null;
    try
    {
      try{}finally{disposable=new ClassThatShouldBeDisposed();}
      //Do your work here
    }
    finally
    {
      if(disposable!=null)
        disposable.Dispose();
    }
    

    Personally I just assume threads never get aborted(except when unloading the AppDomain) and thus write normal using based code.

提交回复
热议问题