c# event handler is called multiple times when event is raised once(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#事件处理程序在一次引发事件时被多次调用
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01