Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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#

You can't. A process is isolated and independent and you can't transfer a thread from one process into another process.

What you could do, however, if you absolutely can't fix the memory leaks internally, is create a watchdog program which launches the app whenever it stops running, and set up your app to only be run in single execution mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top