Bạn chắc chắn phải dọn sạch tham chiếu. Nếu có bất kỳ nghi ngờ nào bạn có thể dễ dàng kiểm tra với sự kiện tĩnh của riêng bạn như vậy.
static class MemoryLeak
{
static List<Action<int>> list = new List<Action<int>>();
public static event Action<int> ActivateLeak
{
add
{
list.Add(value);
}
remove
{
list.Remove(value);
}
}
}
Sau đó, bằng cách thiết lập một breakpoint trong hàm remove bạn có thể thấy rằng các bạn tham khảo được không dọn dẹp.
class Program
{
static void Main(string[] args)
{
foo f = new foo();
MemoryLeak.ActivateLeak += o => f.bar();
f.tryCleanup();
}
}
class foo
{
public void bar()
{ }
public void tryCleanup()
{
MemoryLeak.ActivateLeak -= o => bar();
}
}
Là giải pháp thay thế cho giải pháp của Simon, bạn có thể sử dụng lần đóng thứ hai để tạo ra một hành động "tách rời".
foo f = new foo();
Action<int> callfoo = o => f.bar();
MemoryLeak.ActivateLeak += callfoo;
Action cleanUp =() => MemoryLeak.ActivateLeak -= callfoo;
// Now you can pass around the cleanUp action and call it when you need to unsubscribe from the event.
cleanUp();
Tôi thích phong cách succint ở đây. Đối với nhu cầu của tôi, điều này sẽ hoạt động hoàn hảo. Cảm ơn bạn đã dành thời gian viết bài này! – jschroedl