gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:20:04 25 4
gpt4 key购买 nike

下面是我的代码,第一部分是我引发事件的地方,第二部分是我在另一个类中使用它的地方。看起来很简单,但日志显示即使事件被引发一次,事件也会在使用此事件的类上触发 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# 事件处理程序被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25190270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com