我正试图解决这个问题。下面的代码最终只计算订阅者类类型的垃圾收集对象的数量。当代码如图所示运行时,我得到的 SubscribersClass.Count 值为 0。当我注释掉 EventsClass 中的第一行并取消注释该类的其余部分时,SubscribersClass.Count 的值是 10。
我唯一能想到的是,由于 EventsClass EventHandler 有问题(如图所示),因此实际上没有创建 SubscribersClass 的实例。
希望有人可以帮助我了解到底发生了什么。
这是学术性的,没有实用价值。只是想弄清楚,但到目前为止只设法获得了 GoogleBlisters。
namespace understandingEvents
{
public class EventsClass
{
public event EventHandler SomeEvent; // if this is commented out and
// remainder of class is uncommented
// it works fine
/*
public event EventHandler SomeEvent
{
add
{
Console.WriteLine("An event has been added");
}
remove
{
Console.WriteLine("An event has been removed");
}
}
*/
}
public class SubscribersClass
{
static int count = 0;
static public int Count
{
get { return count; }
}
public SubscribersClass (EventsClass eventPublisher)
{
eventPublisher.SomeEvent += new EventHandler(Subscriber_SomeEvent);
}
~SubscribersClass()
{
Interlocked.Increment(ref count);
}
public void Subscriber_SomeEvent(object sender, EventArgs e)
{
Console.WriteLine("This is an event");
}
}
class Program
{
static void Main(string[] args)
{
EventsClass publisher = new EventsClass();
for (int i = 0; i < 10; i++)
{
SubscribersClass subscriber = new SubscribersClass(publisher);
subscriber = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(SubscribersClass.Count.ToString());
}
}
}