NetworkInformation NetworkStatusChanged 事件触发两次 [英] NetworkInformation NetworkStatusChanged event fired twice
问题描述
我正在使用我认为推荐的方法监听我的 WinRT 应用程序中的网络变化.
I am listening for a network change in my WinRT application using what I believe is the recommended approach.
我使用此代码订阅了该事件.(我已经在很多地方尝试过,但目前我在页面 OnNavigatedTo
方法中使用了它).
I subscribe to the event using this code. (I have tried in a number of places but currently I have it in the page OnNavigatedTo
method).
NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
然后在 OnNvaigatedFrom
方法中我删除它:
Then in the OnNvaigatedFrom
method I remove it:
NetworkInformation.NetworkStatusChanged -= NetworkInformation_NetworkStatusChanged;
当我移除网络电缆时,NetworkInformation_NetworkStatusChanged
事件被正确触发.但是,当我重新插入(重新上线)时,事件被触发两次,我的数据(离线时存储在本地)被上传到服务器两次.
When I remove the network cable the NetworkInformation_NetworkStatusChanged
event is fired correctly. However, when I plug back in (go back online) the event is fired twice and my data (stored locally while offline) gets uploaded to the server twice.
以前有没有人遇到过这种情况/知道为什么会发生这种情况 - 这让我很生气.
Has anybody come across this before/know why it might be happening - its driving me mad.
非常感谢克里斯
推荐答案
在我们的测试中,我们发现每个可用的适配器都会收到一次事件.我们有 5 个适配器,因此每次我们重新插入电缆时,我们似乎都会收到与活动(启用)适配器一样多的事件.我们通过禁用其中一个适配器并将事件数量减少恰好一个来测试这一点,反之亦然.不过,似乎我们只有一个断开连接的事件.
In our testing we found that you will receive the event once per available adapter. We have 5 adapters so every time we plug a cable back in we seem to get an event as many times as there are active (enabled) adapters. We tested this by disabling one of the adapters and the number of the events reduced by exactly one and vice versa. It seems we only get one event for disconnect though.
您的事件多次触发的另一个原因是您的网络确实断开并重新连接.
The other reason for your event to be firing more than once is the fact that your network does actually drops and reconnects.
在任何情况下,您都需要防御性地编写代码来处理实现的现实以及与网络连接相关的普遍不可靠性.
In any case it's on you to write the code defensively to deal with the reality of the implementation and general unreliability associated with network connections.
这篇关于NetworkInformation NetworkStatusChanged 事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!