Skip to content

Proposal: ConditionalWeakReference<TKey, TValue> #30759

Closed

Description

@weltkante

Background

ConditionalWeakTable<TKey, TValue> (CWT) contains a unique GC primitive as its building block called DependentHandle in source code or ephemeron in general. It allows to keep a value alive as long as the key is alive. This functionality is not possible to implement outside the GC so it is a very valuable primitive, just like GCHandle and WeakReference.

However note that GCHandle is public, unlike DependentHandle, so users could implement their own WeakReference implementation if it wouldn't exist. Currently it is not possible to implement your own ConditionalWeakTable because the underlying GC primitive is not exposed.

Compared to WeakReference the desire to implement your own variation of CWT is much higher because it is a complex data structure. While theoretically you can use CWT itself as a building block for your other data structures, since CWT is a collection you have to take a compromise:

  • Create a single shared CWT with the associated lookup overhead and locking contention. If you cannot guarantee that your keys are unique you also have to make the TValue of the CWT a collection which adds another level of indirection and overhead. This is the recommended usage of CWT but its not suited for use cases which are more complex and would be better suited by having an individual reference as building block.
  • Create a CWT for every site where you need a single reference, with the associated unnecessary indirection and overhead.
  • Use reflection to access the native static methods on DependentHandle

The third option is currently by far the preferable one due to the much lower overhead when CWT doesn't provide a fit, though having to poke into runtime internals with reflection also feels wrong.

Note that there is a related but different request #6031 to expose the DependentHandle directly. This proposal is not a duplicate, it adds a currently missing "safe" high level primitive in contrast to exposing the low level primitive of DependentHandle. If it were exposed you could implement the high level primitive yourself, but it would still be valuable to have in the framework, just as you have WeakReference and GCHandle living alongside.

Motivation

We often encounter situations where we want to make use of the GC liveness semantics of a DependentHandle without requiring the lookup semantics of a CWT, so being forced to go through a CWT adds a lot of unnecessary overhead to any implementation wanting to make use of this GC feature.

One particular important example are weak event managers. Historically these have been using WeakReference and regular polling of the table, but these implementations are inferior to a general purpose solution. What you want to say is "keep this delegate alive as long as that other object is not GC'ed", a single DependentHandle would exactly represent this semantic. Note that you don't actually want to lookup events based on their keys, you have a list of DependentHandles as your weak event subscriptions. This is not possible to implement cleanly with the currently exposed ConditionalWeakTable API.

Similar scenarios keep happening over the years, where we just want a list of weak references being kept alive by something else, usually with interfaces instead of delegates, where we want to keep some sort of interface alive as long as something else is still alive.

Proposal

Implement and expose an analogue to WeakReference<T> wrapping the GC primitive used by CWT. I suggest the naming to be ConditionalWeakReference<TKey, TValue> because it accurately represents its semantics and relates in naming to both ConditionalWeakTable and WeakReference.

While you could also expose DependentHandle as analogue to GCHandle I currently have no practical use case for the low level access, all use cases I have encountered would be solvable by having a high level construct of a single conditional reference.

Proposed API

namespace System
{
    public sealed class ConditionalWeakReference<TKey, TValue>
        where TKey : class
        where TValue : class
    {
        public ConditionalWeakReference(TKey key, TValue value);
        ~ConditionalWeakReference();
        public bool TryGetKey(out TKey key);
        public bool TryGetValue(out TValue value);
        public bool TryGetKeyValue(out TKey key, out TValue value);
        public void SetKey(TKey key);
        public void SetValue(TValue value);
    }
}
  • Making the class sealed is symmetric to WeakReference<T>
  • bool IsAlive { get; } is not present on WeakReference<T> either so I omitted it. If you want to implement it, it would be equivalent to calling TryGetKey and discarding the key, like you can do with WeakReference<T>.TryGetTarget.
  • Clearing the reference can be done by SetKey(null) which is the analogue to WeakReference<T>.SetTarget(null)
  • Nullability annotations are missing, they are still new to me.

Reference implementation

expand
namespace System
{
    public sealed class ConditionalWeakReference<TKey, TValue>
        where TKey : class
        where TValue : class
    {
        private DependentHandle _handle;

        public ConditionalWeakReference(TKey key, TValue value)
        {
            if (key is null)
            {
                // if key is null then value also has to be null
                if (!(value is null))
                    throw new ArgumentNullException(nameof(key));
            }
            else
            {
                _handle = new DependentHandle(key, value);
            }
        }

        ~ConditionalWeakReference()
        {
            // ConditionalWeakTable does not free handles during AppDomain shutdown, so we don't do it either
            if (!Environment.HasShutdownStarted)
            {
                lock (this)
                {
                    _handle.Free();
                }
            }
        }

        public bool TryGetKey(out TKey key)
        {
            lock (this)
            {
                if (_handle.IsAllocated)
                {
                    var primary = _handle.GetPrimary();
                    if (primary != null)
                    {
                        key = (TKey)primary;
                        return true;
                    }
                }

                key = default;
                return false;
            }
        }

        public bool TryGetValue(out TValue value)
        {
            lock (this)
            {
                if (_handle.IsAllocated)
                {
                    var primary = _handle.GetPrimaryAndSecondary(out var secondary);
                    if (primary != null)
                    {
                        value = (TValue)secondary;
                        return true;
                    }
                }

                value = default;
                return false;
            }
        }

        public bool TryGetKeyValue(out TKey key, out TValue value)
        {
            lock (this)
            {
                if (_handle.IsAllocated)
                {
                    var primary = _handle.GetPrimaryAndSecondary(out var secondary);
                    if (primary != null)
                    {
                        key = (TKey)primary;
                        value = (TValue)secondary;
                        return true;
                    }
                }

                key = default;
                value = default;
                return false;
            }
        }

        public void SetKey(TKey key)
        {
            lock (this)
            {
                if (key is null)
                {
                    _handle.Free();
                }
                else
                {
                    if (!_handle.IsAllocated)
                        throw new InvalidOperationException();

                    _handle.SetPrimary(key);
                }
            }
        }

        public void SetValue(TValue value)
        {
            lock (this)
            {
                if (!_handle.IsAllocated)
                    throw new InvalidOperationException();

                _handle.SetSecondary(value);
            }
        }
    }
}

Open questions

  • I'm not sure how much sense my reference implementation of SetKey and SetValue makes, they are primitives on DependentHandle so I included them in the API because they are required for being symmetric with WeakReference. If you feel like you don't want that an alternative would be making the class IDisposable instead.
  • Should there be a SetKeyValue(TKey, TValue) to reinitialize the handle without reallocation of the ConditionalWeakReference?
  • Should SetKey(TKey) with non-null key be allowed on an uninitialized handle and (instead of throwing) allocate a new handle with TValue set to null?
  • The lock (this) in my reference implementation is not great. How is WeakReference handling thread safety, does it just delegate to the runtime implementation? It should probably be analogous if possible, but this means the IsAllocated check must happen in DependentHandle or the runtime, not in the caller (invocation on IntPtr.Zero as handle should not throw)

Activity

  1. GSPP commented on Sep 4, 2019

    @GSPP

    Can we get this proposal as well as DependentHandle considered for 5.0? It seems like not too much work needs to be done to expose this. It's a very powerful primitive to have.

    In my opinion, both types should exist in the framework.

  2. transferred this issue fromdotnet/coreclron Sep 4, 2019
  3. stephentoub commented on Sep 4, 2019

    @stephentoub
    Member
  4. transferred this issue fromdotnet/corefxon Feb 1, 2020
  5. added this to the Future milestone on Feb 1, 2020
  6. weltkante commented on Feb 10, 2020

    @weltkante
    ContributorAuthor

    @stephentoub @Maoni0 anything I can do to move this proposal along now that the repo transitions are mostly over? There are open questions to address, in particular its unclear (to me) what the thread safety and failure behavior of DependentHandle is, how it compares to WeakReference and whether it may need to be adjusted (not throwing on zero handles) to make the implementation better than doing a lock(this) like I was doing in the reference implementation.

    We really would like to get this into the framework in the long run, the sooner the better, as there currently is no alternative to doing reflection / dynamic methods calling the internals directly. All alternatives I've come across so far have unacceptable performance overhead compared to this when implementing weak event handling.

  7. added
    untriaged
    on Feb 26, 2020
  8. added
    api-needs-work
    and removed
    untriaged
    on Jul 3, 2020
  9. Maoni0 commented on Jan 4, 2021

    @Maoni0
    Member

    I'm wary of exposing DH because of perf. currently DH handling is not really optimized (especially scanning them which is done during the STW part of a background GC). I do have a design to make it optimized but it's work that didn't make onto our agenda for the near future. I was already seeing DH usage abused via CWT so I didn't want to expose yet more things that use DH.

    I think the usage you mentioned to implement the weak event manager could be provided by the framework as its own thing that uses DH internally and not as easy to abuse.

    the API surface you mentioned is based what it would look like if/when we expose DH.

  10. weltkante commented on Jan 5, 2021

    @weltkante
    ContributorAuthor

    This sounds like you expect having to reshape the infrastructure in order to support this performantly? Otherwise, if the infrastructure is going to remain the same and just needs to be optimized how the GC implements it, there is no harm in exposing it as counterpart to WeakReference. Even then it will only get faster over having to abuse CWT (no lock contention for a shared CWT, less general overhead over a single-entry CWT). But I get that you don't want an easily discoverable API if the underlying implementation is not performant algorithmically and can't support its usage well.

    I don't really understand the desire to only expose complex types built on the primitive though, just like WeakReference this is also a primitive that is valuable in itself (it does have history across languages and in research, see the link to ephemerons). In the original post I've mentioned weak event managers, but literally this is a building block for creating any kind of subscription system that doesn't want to forcefully keep its subscribers alive. Not just for delegates, but also interfaces. If the building block is not exposed people will have to keep abusing the complex classes for things they aren't designed for.

    But thanks for the answer, I assume there is nothing to contribute yet if the infrastructure must be reworked (or reviewed) first. I'll keep watching the issue so please keep it updated in case the situation changes at some point.

  11. Maoni0 commented on Jan 5, 2021

    @Maoni0
    Member

    I don't really understand the desire to only expose complex types built on the primitive though

    I just meant in this case the "complex type" provides the same things we'd provide for a DH. for a DH you also need the Set/Get key/value anyway.

  12. GSPP commented on Jan 6, 2021

    @GSPP

    Is there a technical reason for not exposing it besides the potential for "performance abuse"? I'd argue that developers should be given the ability to shoot themselves in the foot with this rather advanced type.

    Currently, the feature is fully exposed through CWT (right?). It's just that CWT is slower than DH would be standalone.

  13. Maoni0 commented on Jan 6, 2021

    @Maoni0
    Member

    I'd argue that developers should be given the ability to shoot themselves in the foot with this rather advanced type.

    it's definitely possible to argue this in both ways.

    if someone wants to do the work to get an API proposal, get it approved, do the implementation/testing, document it (especially to explain the perf implications), I would support it if the libraries folks also agree it's a good idea. our team currently doesn't have this on our agenda and our schedule is already full for the next release.

  14. removed
    api-suggestion
    on Jun 25, 2021
  15. weltkante commented on Jun 26, 2021

    @weltkante
    ContributorAuthor

    #19459 allows to implement this yourself now, but it is easy to get wrong and risk leaks.

    Not sure if this should be kept open or be closed, I still think there is some value to have a higher level construct (class instead of struct, like WeakReference vs. GCHandle) but it probably should wait until the underlying implementation gets improved. Besides the potential performance issues due to the implementation not scaling up - see discussion above - there is also risk of leaks, see this comment for a summary of issues identified in #12255 and how they would apply here

  16. dotnet-policy-service commented on Dec 26, 2025

    @dotnet-policy-service
    Contributor

    Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.

    This process is part of our issue cleanup automation.

  17. added
    backlog-cleanup-candidate
    on Dec 26, 2025
  18. dotnet-policy-service commented on Jan 10, 2026

    @dotnet-policy-service
    Contributor

    This issue will now be closed since it had been marked no-recent-activity but received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.

  19. removed this from the Future milestone on Jan 10, 2026
  20. locked and limited conversation to collaborators on Feb 9, 2026
  21. removed
    backlog-cleanup-candidate
    on Feb 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions