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

c# event handler is called multiple times when event is raised once(c#事件处理程序在一次引发事件时被多次调用)

本文介绍了c#事件处理程序在一次引发事件时被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码,第一部分是我引发事件的地方,第二部分是我在另一个类中使用它的地方.看起来很简单,但日志显示即使事件被引发一次,事件在使用该事件的类上触发了 20 多次.有什么想法吗?

Below is my code, first is where I raise the event and second section is where I consume it in another class. It seems pretty straight forward, but the logs are showing that even though the event is raised once, the event is firing 20+ times on the class that consumes this event. Any ideas?

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 事件的类:

Class that uses IBSerialPort and consumes its OnPacketReceived Event:

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!!!!");
}

推荐答案

试试这个,这将取消注册任何 prev 订阅者:

Try this, this will unregister any prev subscriber:

ibSerialPort.OnPacketReceived -= ibSerialPort_OnPacketReceived;   // unregister
ibSerialPort.OnPacketReceived += ibSerialPort_OnPacketReceived;  //register

这篇关于c#事件处理程序在一次引发事件时被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:c#事件处理程序在一次引发事件时被多次调用

基础教程推荐