how to keep assemblyloadcontext delay gc collected after call unload method #113115
-
how to keep assemblyloadcontext delay gc collected after call unload method? our situation: the collectiable assembmlyloadcontext ALC1 loading some assembly A1.dll and A2.dll we want the ALC1 object delay been gc collected, we create strong gchandle with Assembly A1 and A2 object before call but it not work. the ALC1 object will be collected when gc occur. the detail about our code flow:
what excatly solution solving the situation? |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 11 replies
-
The description and the code comment doesn't match. When assemblies are alive, the ALC will also be kept alive. It won't be collected before freeing handles of assembly. There's nothing keeping it alive after handles of assembly are freed, and it will be collected as expected. What are you trying to achieve here? Why do you need to keep the ALC alive without keeping the loaded stuff alive? |
Beta Was this translation helpful? Give feedback.
-
I print the execute stack log:
|
Beta Was this translation helpful? Give feedback.
-
I have tried to new gchandle of ALC object, also can't keep it alive. ALC.Unload();
GCHandle.Alloc(ALC, GCHandleType.Normal);
new UnloadSentinal(ALC, OnALCDelete); |
Beta Was this translation helpful? Give feedback.
-
as this issuse said, the new gchandle of assembly can't keep the alc alive #40547 but I new gchandle on alc, still been collected. |
Beta Was this translation helpful? Give feedback.
-
There may be a bit of confusion here. The Calling the The only added value of So to your initial question, keeping GCHandles referencing assemblies in the |
Beta Was this translation helpful? Give feedback.
-
If you want to understand the internals of how it all works, you can take a look at the https://github.com/dotnet/runtime/blob/main/docs/design/features/unloadability.md document that describes its internals. |
Beta Was this translation helpful? Give feedback.
I see two more problems with the
UnloadSentinel
class as written:WeakReference
class it is using gets finalized and cleared before theUnloadSentinel
class. SoUnloadSentinel
is detecting the unload early. In general it is recommended to not use other managed classes in a finalizer, as the order of finalization is not guaranteed.alc
primary constructor variable keeps the ALC alive.Here is a test program and a version of
UnloadSentinel
that solves these two problems.