下面是我的代码,第一部分是我引发事件的地方,第二部分是我在另一个类中使用它的地方。看起来很简单,但日志显示即使事件被引发一次,事件在使用该事件的类上触发了 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!!!!");
}