5

假设我有WeakReference一个目标强引用。我想在目标对象本身被 GC 收集时得到通知。可能吗?

编辑:将代码添加到终结器/析构函数不是这里的选项。我需要一些不依赖于类代码的东西。

4

3 回答 3

7

在 .NET 4.0 和以下使用 .NET 下是可能的ConditionalWeakTable<TKey, TValue>。感谢这个其他网站。它遵循概念验证代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

namespace Test
{
    public static class GCInterceptor
    {
        private static ConditionalWeakTable<object, CallbackRef> _table;

        static GCInterceptor()
        {
            _table = new ConditionalWeakTable<object, CallbackRef>();
        }

        public static void RegisterGCEvent(this object obj, Action<int> action)
        {
            CallbackRef callbackRef;
            bool found = _table.TryGetValue(obj, out callbackRef);
            if (found)
            {
                callbackRef.Collected += action;
                return;
            }

            int hashCode = RuntimeHelpers.GetHashCode(obj);
            callbackRef = new CallbackRef(hashCode);
            callbackRef.Collected += action;
            _table.Add(obj, callbackRef);
        }

        public static void DeregisterGCEvent(this object obj, Action<int> action)
        {
            CallbackRef callbackRef;
            bool found = _table.TryGetValue(obj, out callbackRef);
            if (!found)
                throw new Exception("No events registered");

            callbackRef.Collected -= action;
        }

        private class CallbackRef
        {
            private int _hashCode;
            public event Action<int> Collected;

            public CallbackRef(int hashCode)
            {
                _hashCode = hashCode;
            }

            ~CallbackRef()
            {
                Action<int> handle = Collected;
                if (handle != null)
                    handle(_hashCode);
            }
        }
    }
}

使用以下代码进行测试:

public partial class Form1 : Form
{
    private object _obj;

    public Form1()
    {
        InitializeComponent();

        _obj = new object();

        _obj.RegisterGCEvent(delegate(int hashCode)
        {
            MessageBox.Show("Object with hash code " + hashCode + " recently collected");
        });
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _obj = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
于 2012-03-13T20:52:04.030 回答
2

Object.Finalize()方法呢?不会在最终确定时调用吗?

于 2011-12-28T10:48:07.243 回答
0

您可以使用拦截来捕获从自定义接口/类继承的每个类的 Finalize。我想,这就是你想要达到的目标,对吧?为此,您可以使用 Unity。是一个非常简短的示例,如何使用 Unity 进行拦截。

于 2011-12-28T11:07:04.580 回答