C#:收集 WeakReference 之前的通知?

2024-01-04

在C#/.NET中,有什么方法可以在弱引用指向的对象被破坏之前获得通知吗?基本上,我想允许收集一个对象,但在对象被销毁之前做一些事情,而不修改代码来添加析构函数(因为我不知道我的代码将起诉什么类型的对象)。

谢谢, 罗伯特


.Net 4.0 拥有您需要的解决方案:条件弱表 http://msdn.microsoft.com/en-us/library/dd287757.aspx。这是一个演示这个想法的简短程序。 (讨论过here http://www.facebook.com/note.php?note_id=327114446573以及)

using System;
using System.Runtime.CompilerServices;

namespace GCCollectNotification
{
    class ObjectToWatch { }

    class Notifier
    {
        public object ObjectToWatch { get; set; }
        ~Notifier() { Console.WriteLine("object is collected"); }
    }

    class Program
    {
        private ConditionalWeakTable<object, Notifier> map
            = new ConditionalWeakTable<object, Notifier>();

        public void Test()
        {
            var obj = new ObjectToWatch();
            var notifier = map.GetOrCreateValue(obj);
            notifier.ObjectToWatch = obj;
        }

        static void Main(string[] args)
        {
            new Program().Test();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            // "object is collected" should have been printed by now

            Console.WriteLine("end of program");
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C#:收集 WeakReference 之前的通知? 的相关文章

随机推荐