下面是我的代码,首先是我提出事件的地方,第二部分是我在另一个类中使用它的地方.它看起来很简单,但是日志显示即使事件被提升一次,事件也会在消耗此事件的类上触发20次.有任何想法吗?
IBSerialPort类:
public delegate void PacketReceivedHandler(object sender,PacketReceivedEventArgs e); public event PacketReceivedHandler OnPacketReceived; public class PacketReceivedEventArgs : EventArgs { public Packet PacketReceived { get; private set; } public PacketReceivedEventArgs(Packet packet) { PacketReceived = packet; } } // raise event if (OnPacketReceived != null) { Log("This is only called ONCE!"); PacketReceivedEventArgs args = new PacketReceivedEventArgs(data); OnPacketReceived(this,args); }
使用IBSerialPort并使用其OnPacketReceived事件的类:
IBSerialPort ibSerialPort = null; .. if (ibSerialPort == null) { Log("This is only called once"); ibSerialPort = IBSerialPort.Instance; ibSerialPort.OnPacketReceived += ibSerialPort_OnPacketReceived; } void ibSerialPort_OnPacketReceived(object sender,IBSerialPort.PacketReceivedEventArgs args) { Log("This is called ~25 times!!!!"); }