views:

108

answers:

2

I have an assembly that when accessed spins up a single thread to process items placed on a queue. In that assembly I attach a handler to the DomainUnload event:

AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);

That handler joins the thread to the main thread so that all items on the queue can complete processing before the application terminates.

The problem that I am experiencing is that the DomainUnload event is not getting fired when the console application terminates. Any ideas why this would be?

Using .NET 3.5 and C#

+6  A: 

Unfortunately for you, this event is not raised in the default AppDomain, only in app domains created within the default one.

From the MSDN documentation:

This event is never raised in the default application domain.

Rob Levine
+1  A: 

You'll need to subscribe the event for the specific domain. You also can't rely on the domain get unloaded at termination time. Remove the comment from this code to see that:

using System;
using System.Reflection;

class Program {
    static void Main(string[] args) {
        var ad = AppDomain.CreateDomain("test");
        ad.DomainUnload += ad_DomainUnload;
        //AppDomain.Unload(ad);
        Console.ReadLine();
    }
    static void ad_DomainUnload(object sender, EventArgs e) {
        Console.WriteLine("unloaded, press Enter");
        Console.ReadLine();
    }
}
Hans Passant