Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# code to execute code in another application domain?

I have a program that executes for 24 hours, then restarts.

How can I shift main() from into a separate application domain, which is torn down and refreshed every 24 hours, in order to completely eliminate any potential memory leaks?

like image 637
Contango Avatar asked Nov 28 '22 17:11

Contango


2 Answers

You had me right up until you said:

in order to completely eliminate any potential memory leaks?

If you want to run code in another app domain then there are plenty of resources on how to do this, for example Executing Code in Another Application Domain (C# and Visual Basic). The basic principle is to create a class that inherits from MarshalByRefObject. You then create your new app domain and instruct it to create an instance of that object - this object is then your "entry point" into your app domain:

AppDomain newAppDomain = AppDomain.CreateDomain("NewApplicationDomain");
ProxyObject proxy = (ProxyObject)newAppDomain.CreateInstanceAndUnwrap("MyAssembly", "MyNamespace.MyProxy");

However in C# there isn't really any such thing as a "memory leak", at best you just have objects which are inadvertantly kept in scope. If this is the case then an app domain is just overkill - all you really need to do is remove references to managed objects that are no longer needed and the Garbage Collector will tidy them up for you.

If you have a true memory leak in unmanaged code an app domain won't help you either. Unmanaged types aren't bounded by app domains and so any unmanaged memory allocated "inside" the app domain won't be freed when the app domain is destroyed. In this case you would be better off using separate processes instead.

like image 172
Justin Avatar answered Dec 01 '22 08:12

Justin


I've created a class that allows you to execute code in a separate application domain which would allow you to dispose the application domain and recreate it: Executing Code in a Separate Application Domain Using C#

like image 36
Keith Avatar answered Dec 01 '22 07:12

Keith