How does AppDomain.Unload () interrupt threads?

According to multiple resources (e.g. MSDN and CLR via C #), when we call AppDomain.Unload (userDomain), threads in userDomain will be forced to throw ThreadAbortException, which cannot be stopped untile, we call Thread.ResetAbort, So I tried the below code to witness my cancellation. One thread created in the default domain runs the code below to call the FooType object, which is created in another domain (i.e. in the 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"); } 

Below is the Foo.Run code (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 userDomain, I was surprised that a ThreadAbortException was detected only in FooType: Run () (which is in userDomain), but not in ThreadRun () (which is in defaultDomain). And ThreadRun () receives only the AdDomainUnlo adException application, and then continues to work.

If I tried to directly interrupt the thread without unloading the domain, a ThreadAbortException was thrown in both places.

I wonder if this difference should happen? Many thanks

+6
source share
1 answer

When unloading userDomain, the thread that is currently running in this domain receives an AbortException. However, the same stream "to" another AppDomain too (main). With AppDomains as data delimiters, but not for execution delimiters, the CLR cannot interrupt the thread that spawns multiple AppDomains. That is why you will only get UnloadedException.

When you call Thread.Abort, you explicitly interrupt the thread, in relation to AppDomain it is currently located.

In any case, you do not want your thread to be interrupted when all you wanted to do was unload some AppDomain.

+1
source

Source: https://habr.com/ru/post/891196/


All Articles