Có thể theo .NET 4.0 và sau bằng cách sử dụng ConditionalWeakTable<TKey, TValue>
. Cảm ơn this và other trang web. Nó sau chứng minh mã khái niệm:
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);
}
}
}
}
Thử nghiệm với đoạn mã sau:
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();
}
}
Tôi không tin có bất kỳ sự kiện lớn lên mà chỉ một địa chỉ đang được thu thập. Điều gần nhất bạn có thể thử là tạo một Trình hoàn tất trên loại đang được tham chiếu, mặc dù chúng chạy trước một thời gian không xác định trước khi bộ sưu tập xảy ra. Tôi mong ai đó thông minh hơn đưa ra câu trả lời. –
Các destructor của đối tượng của bạn được gọi là nếu thu gom rác phá hủy nó. Bạn có thể phản ứng trong cuộc gọi destructor và gửi một sự kiện tự tạo ví dụ. –
Âm thanh như một công thức để phục sinh. Tại sao bạn cần điều này? – Ani