Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppDomain.CurrentDomain.DomainUnload not be raised in Console app

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#

like image 987
Guy Avatar asked Apr 22 '10 17:04

Guy


2 Answers

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.

like image 195
Rob Levine Avatar answered Oct 13 '22 01:10

Rob Levine


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();
    }
}
like image 33
Hans Passant Avatar answered Oct 12 '22 23:10

Hans Passant