There have been quite a few improvements under the System.Net namespace in .NET 2.0. One of those improvements is the addition of a NetworkChange class which lives under the System.Net.NetworkInformation namespace along with a whole heap of other useful network diagnostic classes.
The NetworkChange class is really a god-send for “smart client” developers who need to deal with transient network connectivity which you might find if you are using GPRS connections, wireless hotspots or even the in-house wireless LAN. The NetworkChange class exposes two events, NetworkAvailabilityChanged and NetworkAddressChanged. All you have to do is wire up to these events and get notified when things like wireless networks drop out or you switch physical segments.
To demonstrate how this worked I produced a simple little program that grabs quotes from this web-service (thanks to Swanand Mokashi) and displays them on a label on a form. That form has a status bar which displays the current connectivity status as notified by the NetworkChange class.
Now I know what you are all thinking – you are thinking – “Mitch, you are such a wonderful artist, that green light looks fantastic”. Well, as a matter of fact I wasn’t the artist, it was the icon designer that works for WinZip (great tool – go and buy it now). Ahem – back to the topic of converstation. When I disconnect the network cable or pull out the wireless adapter, I get this screen.
One interesting side note is that it appears that when using a wired connection I only seem to get notified when I next try to use the network, whereas with the wireless connection it pretty much happened straight away. The code to rig all of this up is pretty simple.
Hrm – that looks a little bit wacky doesn’t it? Well thats because I am being a good boy and am dealing with the UI threading issues in Windows Forms by marshalling the UI updates on to the right thread – the NetworkAvailabilityChanged event could come in on any thread, so you generally can’t update the UI from there. Well – thats pretty much it – if you want to see all of the code you can download it here.
Coincidentally it also uses the BackgroundWorker component triggered from the Timer to do the actual web-service call which shows how the BackgroundWorker component can be used to manage asynchronous work and get UI updates happening on the right thread.