Bug in WeakAction in case of Closure Action

前端 未结 3 2269
你的背包
你的背包 2021-02-18 18:39

In one of the projects I take part in there is a vast use of WeakAction. That\'s a class that allows to keep reference to an action instance without causing its tar

3条回答
  •  眼角桃花
    2021-02-18 19:11

    You want to extend the lifetime of the closure class instance to be exactly the same that the A instance has. The CLR has a special GC handle type for that: the Ephemeron, implemented as internal struct DependentHandle.

    1. This struct is only exposed as part of the ConditionalWeakTable class. You could create one such table per WeakAction with exactly one item in it. The key would be an instance of A, the value would be the closure class instance.
    2. Alternatively, you could pry open DependentHandle using private reflection.
    3. Or, you could use one globally shared ConditionalWeakTable instance. It probably requires synchronization to use. Look at the docs.

    Consider opening a connect issue to make DependentHandle public and link to this question to provide a use case.

提交回复
热议问题