0

I have a dynamic-linked library in C# that will be loaded by other libs or apps. The init function needs to be called to allocate/initialize resources when the assembly(dll) is loaded and the cleanup function needs to be invoked before the assembly is unloaded.

I am looking for something in C# that is similar to DllMain function in C++ that you can call functions in the event of DLL_PROCESS_ATTACH and DLL_PROCESS_DETACH.

Thanks in advance.

Steve Lillis
  • 3,263
  • 5
  • 22
  • 41
user2391685
  • 1,006
  • 12
  • 16
  • You should follow this link http://stackoverflow.com/questions/8206736/c-sharp-equivalent-of-dllmain-in-c-winapi – Julian Cr Jul 14 '14 at 23:31
  • @JulianCr I am using the static constructor now, but how about the cleanup function? where should I put it? I am wondering if there is any alternatives. – user2391685 Jul 15 '14 at 03:23

1 Answers1

0

it depends on your scenario.

You can use the AppDomain.ProcessExit event in the static constructor.

something like:

 class MyClass  {    
      static MyClass() {
           AppDomain.CurrentDomain.ProcessExit +=
               MyClass_Dtor;    }

       static void MyClass_Dtor(object sender, EventArgs e) {
            // do here some clean up   
  } 
}

The AppDomain.ProcessExit is not guaranteed to be called.

See more details about AppDomain.ProcessExit here

AppDomain.ProcessExit

Julian Cr
  • 66
  • 2