Skip to content

how to detect AssemblyLoadContext been gc #111116

Answered by huoyaoyuan
srxqds asked this question in General
Discussion options

You must be logged in to vote

Unloading will prevent further usage of the ALC. It will be fully unloaded when all existing usages are dead.
You can use a weak reference to the ALC, and check the weak reference when GC happens. Something like this:

alc.Unloading += alc => _ = new UnloadSentinal(alc);

class UnloadSentinal(AssemblyLoadContext alc)
{
    private readonly WeakReference<AssemblyLoadContext> wr = new(alc);

    ~UnloadSentinal()
    {
        if (!wr.TryGetTarget(out _))
        {
            // Real unload handling
        }
        else
        {
            GC.ReRegisterForFinalize(this);
        }
    }
}

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@srxqds
Comment options

@huoyaoyuan
Comment options

Answer selected by srxqds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants