Event Handler is executed more than once

家住魔仙堡 提交于 2020-01-07 02:52:11

问题


When I use this snippet of code The MessageOutput.Text is set 2 times, which means that the code is executed twice since I don't set the MessageOutput.Text anywhere else. Whenever I get a new message, this method is called and it is supposed to update the UI. Why is this happening and how can I fix it?

 async void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
    {
        uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength;
        string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength);

        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            MessageOutput.Text += (receivedMessage + "\n");
        });
    }

回答1:


Why is this happening and how can I fix it

The most possible reason is, there are several virtual network switches in your system.

For example, there are three virtual network switches in my Windows 10, just go to Control Panel->Network and Internet->Network Connections.

I will get three messages at the same time:

Debug.WriteLine("Received data from remote peer (Remote Address: " +
                    eventArguments.RemoteAddress.CanonicalName + ", Remote Port: " +
                    eventArguments.RemotePort + "): \"" + receivedMessage + "\"");

Received data from remote peer (Remote Address: 169.254.146.116, Remote Port: 22113): "Hello" Received data from remote peer (Remote Address: 172.16.80.1, Remote Port: 22113): "Hello" Received data from remote peer (Remote Address: 10.168.177.14, Remote Port: 22113): "Hello"

Please type ipconfig /all in cmd to check the IPv4 addresses for these switches:




回答2:


I suspect the problem is in this line.

listenerSocket.MessageReceived += MessageReceived;

Please add the code where you have binded this event handler. Because exceptionally this line executed 2 times. So that's why your event handler gets executed twice.Hence you have to figure it out why this event is binded twice and your problem would be resolved. Hope this help !!!



来源:https://stackoverflow.com/questions/38684400/event-handler-is-executed-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!