beefsupreme
beefsupreme

Reputation: 125

When does the garbage collector collect instances created with AppDomain.CreateInstance?

In my application I create a new AppDomain. I then create an instance of a type that inherits from MarshalByRefObject in the AppDomain using CreateInstanceAndUnwrap and assign it to a variable in the default AppDomain. For the sake of the example, I'll call the object "ObjectA".

Correct me if I'm wrong, but if I remove all references to ObjectA in the default AppDomain and the child AppDomain, I'd expect the garbage collector to collect ObjectA. However if ObjectA is created and it spins up a Thread or long-running Task that never exits, I wouldn't expect the garbage collector to collect it.

Is there any way to tell the garbage collector to collect an object in a different AppDomain? Or am I forced to unload the AppDomain?

Upvotes: 0

Views: 392

Answers (1)

Rhys Bevilaqua
Rhys Bevilaqua

Reputation: 2167

If you are running a thread that has a reference to the object then you have left one reference to that object in the appdomain, until the thread exits you won't have it collected.

My suggestion would be to make the object implement IDisposable and have it cancel the long running task/thread when it is called.

Upvotes: 1

Related Questions