Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does AppDomain.Unload() abort the threads?

Tags:

c#

.net

appdomain

According muliple resources (e.g., MSDN and CLR via C#), when we call AppDomain.Unload(userDomain), the threads in the userDomain will be forced to throw ThreadAbortException, which can't be stoped untile we call Thread.ResetAbort. So I tried the below code to testify my undersanding. One thread, created in the default domain, runs the below code to invokefoo object of FooType which is created in another domain (i.e, user domain)

    void ThreadRun(object o)
    {       
           try 
           {
                // this call will cross the App domain;
                foo.Run();
            }
            catch (AppDomainUnloadedException EXP)
            {                    
                 Console.WriteLine("Get appdomain unload exception");
            }
            catch (ThreadAbortException EXP)
            {                    
                Console.WriteLine("Get threadAbortException in ThreadRun");
            }
            Console.WriteLine("Strange, this thread is still alive");
     }

The Foo.Run code is listed below (it does nothing but just sleep)

public class FooType : MarshalByRefObject {
  public void Run()
  {
    try
    {
        Console.WriteLine("Foo.Run is running at " + Thread.GetDomain().FriendlyName);
        Thread.Sleep(TimeSpan.FromSeconds(1500));
    }
    catch (ThreadAbortException)
    {
        Console.WriteLine("get thread abort exception");
    }
  }
}

IF I tried to Unload the userDomain,I was surprised that the ThreadAbortException was caught only in FooType:Run() (which is in the userDomain), but not in ThreadRun() method (which is in the defaultDomain). And ThreadRun() only get AppDomainUnlo adException and then keep running.

If I tried to directly abort the thread without unloading the domain, the ThreadAbortException were acought in both places.

I wonder if this difference is supposed to happend? Thanks a lot

like image 919
Wei Lu Avatar asked Jun 23 '11 09:06

Wei Lu


1 Answers

When you unloading userDomain, thread that is currently working in that domain gets an AbortException. However, the very same thread is "in" another AppDomain too (main). Having AppDomains as data separators, but not execution separators, CLR cannot abort thread that is spawning multiple AppDomains. This why you'll get only UnloadedException.

When you calling to Thread.Abort - you are explicitly aborting the execution of a thread, regardles of AppDomain it is currently into.

Anyway, you would not want your thread being aborted when all you wanted to do is to unload some AppDomain.

like image 76
DiVan Avatar answered Nov 27 '22 11:11

DiVan