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?
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.
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#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With