c# - C#OnReceived事件被触发两次

c# - C#OnReceived事件被触发两次,第1张

我对C#比较陌生,偶然发现了我的onreceived事件被触发两次但第一次没有更新订阅者而只是第二次更新的问题。以下是我的程序中使用的一些代码。感谢是否有人可以看看并告诉我原因在哪里。

我有类似的东西。

public TCPMain()
    {
        SocketService.TCPClient.onConnected  = new SocketService.TCPClient.onConnectedHandler(Client_onConnected);
        SocketService.TCPClient.onDataReceived  = new SocketService.TCPClient.onDataReceivedHandler(Client_onDataReceived);
        SocketService.TCPClient.onDisconnected  = new SocketService.TCPClient.onDisconnectedHandler(Client_onDisconnected);
        SocketService.TCPClient.onStatus  = new SocketService.TCPClient.onStatusHandler(Client_onStatus);
        SocketService.TCPClient.onStatus2  = new SocketService.TCPClient.onStatus2Handler(Client_onStatus2);
    }

    public TCPMain(string RemoteServerIP, int RemoteServerPort, int RemoteServerPort2, string LocalIP = "", int LocalPort = 0)
    {
        this.RemoteServerIP = RemoteServerIP;
        this.RemoteServerPort = RemoteServerPort;
        this.RemoteServerPort2 = RemoteServerPort2;
        this.LocalIP = LocalIP;
        this.LocalPort = LocalPort;

        SocketService.TCPClient.onConnected  = new SocketService.TCPClient.onConnectedHandler(Client_onConnected);
        SocketService.TCPClient.onDataReceived  = new SocketService.TCPClient.onDataReceivedHandler(Client_onDataReceived);
        SocketService.TCPClient.onDisconnected  = new SocketService.TCPClient.onDisconnectedHandler(Client_onDisconnected);
        SocketService.TCPClient.onStatus  = new SocketService.TCPClient.onStatusHandler(Client_onStatus);
        SocketService.TCPClient.onStatus2  = new SocketService.TCPClient.onStatus2Handler(Client_onStatus2);
    }

然后我在虚拟

上创建了一些东西
    public delegate void onReceivedHandler(string Key, string value);
    public event onReceivedHandler OnReceived;

    public delegate void onDataReceivedHandler(string Message);
    public event onDataReceivedHandler onDataReceived;

    public virtual void RaiseOnDataReceived(string Message)
    {
        if (onDataReceived != null)
            onDataReceived(Message);
    }

当触发接收的事件时,将调用以下函数

    void Client_onDataReceived(string Message)
    {
        try
        {
            RaiseOnDataReceived(Message);
            Message = Message.TrimEnd();
            string[] _strParts = null;
        }
     }

当一条新消息到达时,会触发Client_onDataReceived,然后从TCPMain调用RaiseOnDataReceived并引用虚拟。问题是当它到达虚拟时,onDataReceived是= null,因此它返回到客户端并执行其余的编码。第二次触发事件时,onDataReceived是=某事,但当时只发送了一条消息。

最佳答案:

0 个答案:

没有答案
本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复