当事件被引发一次时,多次调用c#事件处理程序

前端之家收集整理的这篇文章主要介绍了当事件被引发一次时,多次调用c#事件处理程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面是我的代码,首先是我提出事件的地方,第二部分是我在另一个类中使用它的地方.它看起来很简单,但是日志显示即使事件被提升一次,事件也会在消耗此事件的类上触发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!!!!");
}

解决方法

试试这个,这将取消注册任何普通用户
ibSerialPort.OnPacketReceived -= ibSerialPort_OnPacketReceived;   // unregister
ibSerialPort.OnPacketReceived += ibSerialPort_OnPacketReceived;  //register

猜你在找的C#相关文章