I’m curious about shared/static object lifetime in an AppDomain where the RemotingCalls are the cause of creating the shared objects.
We’re using a Remoting setup that uses client activated objects of wich we only use the functions to reach into the server. The remoting objects are setup as singletons.
The server setups a channel and uses RemotingConfiguration.Configure to load a configuration file.
Some of these server functions touch and use some static (shared in vb.net) variables on the server. I can’t find out what the lifetime of these static variables is, they get created (static constructor is run) when they’re touched for the first time. Using logging I can’t see the objects dispose/finalize happen.
Waiting for a couple of minutes after connecting to the remoting server sees the shared objects alive and well.
The question:
So what is the expected live time of static objects in this remoting setup. Do they live as long as the AppDomain or do they get cycled out when the Remoting objects get swapped. And what is the correct way to extend their lifetime if needed?
The answer:
Static types live in AppDomain since they accessed the first time till AppDomain is unloaded. So you don’t need to extend their lifetime as long as AppDomain is running.
Static fields are never garbage-collected. Take a look at Jeffrey Richter’s article.
Static fields are considered as a root by Garbage Collector, so Garbage Collector will always assume that static fields are used.
Static fields are initialized when owner type is loaded. JIT compiler loads type on when it needs to build a method and sees reference to this type. Once loaded, the type stays there for all AppDomain lifespan, hence anything referenced by the fields that belong to the type (static fields) will be considered as used references and will not be garbage collected.
Also, regarding this statement:
Technically static variable aren’t necessarily ‘touched’ the first time in static constructor. Consider class like this:
Static constructor (type constructor) will not be ever called, unless you have the code that is executing and referencing this type like
var x = Test.myType;. Well, this probably depends on what ‘touched’ exactly means.The answer:
Static types live in AppDomain since they accessed the first time till AppDomain is unloaded. So you don’t need to extend their lifetime as long as AppDomain is running.