本文介绍了事件处理程序被执行不止一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用这段代码时,MessageOutput.Text设置为2次,这意味着代码执行两次,因为我没有设置其他任何地方的MessageOutput.Text。每当我收到一个新消息,这个方法被调用,它应该是更新UI。为什么会发生这种情况,如何修复?

  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 +\\\
);
});
}


解决方案

最可能的原因是有几个



我将同时收到三条消息:

  Debug.WriteLine(从远程对等体接收数据(远程地址:+ 
eventArguments.RemoteAddress.CanonicalName +,远程端口:+
eventArguments.RemotePort +):\+ receivedMessage +\);

从远程对等体接收的数据(远程地址: 169.254.146.116 远程端口:22113):Hello
从远程对等体接收到的数据(远程地址: 172.16.80.1 ,远程端口:22113):Hello
接收到的数据来自远程对等体(远程地址: 10.168.177.14 ,远程端口:22113):您好



请输入 ipconfig / all 在cmd中检查这些开关的IPv4地址:




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");
        });
    }
解决方案

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:

这篇关于事件处理程序被执行不止一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:48