问题
I am listening for a network change in my WinRT application using what I believe is the recommended approach.
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;
Then in the OnNvaigatedFrom method I remove it:
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.
Many thanks Chris
回答1:
I remember this being an issue. Seems like it still is.
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/520ea5e2-cc17-486d-815e-528ca041d77f/
To solve your problem, keep track of the network availability with a flag and only update if the previous network status was unavailable.
回答2:
In out testing we found that you will receive the even 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 verse. It seems we only get one event for disconnect though.
The other reason for you event to be firing more than once is the fact that your network does actually drops and reconnects.
In any case its on you to write the code defensively to deal with the reality of the implementation and general unreliability associated with network connections.
来源:https://stackoverflow.com/questions/14321289/networkinformation-networkstatuschanged-event-fired-twice