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

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

概述下面是我的代码,首先是我提出事件的地方,第二部分是我在另一个类中使用它的地方.它看起来很简单,但是日志显示即使事件被提升一次,事件也会在消耗此事件的类上触发20次.有任何想法吗? IBSerialPort类: public delegate void PacketReceivedHandler(object sender, PacketReceivedEventArgs e);public ev 下面是我的代码,首先是我提出事件的地方,第二部分是我在另一个类中使用它的地方.它看起来很简单,但是日志显示即使事件被提升一次,事件也会在消耗此事件的类上触发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 eventif (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;   // unregisteribSerialPort.OnPacketReceived += ibSerialPort_OnPacketReceived;  //register
总结

以上是内存溢出为你收集整理的当事件被引发一次时,多次调用c#事件处理程序全部内容,希望文章能够帮你解决当事件被引发一次时,多次调用c#事件处理程序所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1259395.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存