Checking the Internet connection type on Windows Phone
This article explains how to get the Internet connection type without blocking the UI.
Article Metadata
Code Example
Tested with
Compatibility
Platform Security
Article
Contents |
Introduction
All Windows Phone applications that use Internet data should always check if there is a valid Internet connection; if there is no connection, a proper message should be displayed to the user. The correct way to check if you have an Internet connection (WIFI, Ethernet, or none) is by checking the property:
NetworkInterface.NetworkInterfaceType
Unfortunately checking this property is a synchronous operation, so calling it in the UI thread can block the UI for many seconds.
This code example provides a utility class you can use to check the interface type in another thread, and shows how you can use this class in your UI.
Utility class for checking the connection
The utility class below (included in the sample project) checks the network connection in another thread.
using System.Threading;
using Microsoft.Phone.Net.NetworkInformation;
namespace DotNetApp.Utilities
{
public class NetworkTypeEventArgs
{
#region Constructor
public NetworkTypeEventArgs(NetworkInterfaceType type, bool hasTimeout = false)
{
Type = type;
HasTimeout = hasTimeout;
}
#endregion
#region Properties
public bool HasTimeout { get; private set; }
public bool HasInternet
{
get { return Type != NetworkInterfaceType.None; }
}
public NetworkInterfaceType Type { get; private set; }
#endregion
}
/// <summary>
/// Static class to get the NetworkInterfaceType without blocking the UI thread.
/// </summary>
public static class NetworkInformationUtility
{
#region Fields
private static bool _isGettingNetworkType;
private static readonly object _synchronizationObject = new object();
private static Timer _timer;
#endregion
#region Methods
/// <summary>
/// Get the NetworkInterfaceType asynchronously.
/// </summary>
/// <param name="timeoutInMs">Specifies the timeout in milliseconds.</param>
public static void GetNetworkTypeAsync(int timeoutInMs)
{
lock (_synchronizationObject)
{
if (!_isGettingNetworkType)
{
_isGettingNetworkType = true;
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
Thread thread = new Thread(GetNetworkType) {IsBackground = true};
thread.Start(timeoutInMs);
}
else
{
FireGetNetworkTypeCompleted(NetworkInterfaceType.None);
}
}
}
}
#endregion
#region Delegates
public delegate void NetworkTypeEventHandler(object sender, NetworkTypeEventArgs networkTypeEventArgs);
#endregion
#region Events
public static event NetworkTypeEventHandler GetNetworkTypeCompleted;
#endregion
#region Event Handlers
private static void OnTimerElapsed(object state)
{
FireGetNetworkTypeCompleted(NetworkInterfaceType.None, true);
}
#endregion
#region Private Methods
private static void GetNetworkType(object state)
{
_timer = new Timer(OnTimerElapsed, null, (int)state, 0);
// This is a blocking call, this is why a thread is used to let the UI to be fluid
NetworkInterfaceType type = NetworkInterface.NetworkInterfaceType;
_timer.Dispose();
_timer = null;
FireGetNetworkTypeCompleted(type);
}
private static void FireGetNetworkTypeCompleted(NetworkInterfaceType type, bool hasTimeout = false)
{
lock (_synchronizationObject)
{
if (_isGettingNetworkType)
{
_isGettingNetworkType = false;
NetworkTypeEventHandler networkTypeEventHandler = GetNetworkTypeCompleted;
if (networkTypeEventHandler != null)
{
networkTypeEventHandler(null, new NetworkTypeEventArgs(type, hasTimeout));
}
}
}
}
#endregion
}
}
Using the utility class
Here are the steps to use this class in your code:
- Add the NetworkInformationUtility.cs to your project.
- Attach method to the event NetworkInformationUtility.GetNetworkTypeCompleted.
- Call NetworkInformationUtility.GetNetworkTypeAsync(3000 /*timeout in ms*/);
- Retrieve the result on the GetNetworkTypeCompleted method that you attached to the event.
Code sample:
using System.Windows;
using DotNetApp.Utilities;
namespace NetworkInformationApp
{
public partial class MainPage {
public MainPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
NetworkInformationUtility.GetNetworkTypeCompleted += GetNetworkTypeCompleted;
NetworkInformationUtility.GetNetworkTypeAsync(3000); // Timeout of 3 seconds }
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
NetworkInformationUtility.GetNetworkTypeCompleted -= GetNetworkTypeCompleted;
}
private void GetNetworkTypeCompleted(object sender, NetworkTypeEventArgs networkTypeEventArgs)
{
string message;
if (networkTypeEventArgs.HasTimeout)
{
message = "The timeout occurred";
}
else if (networkTypeEventArgs.HasInternet)
{
message = "The Internet connection type is: " + networkTypeEventArgs.Type.ToString();
}
else {
message = "There is no Internet connection";
}
// Always dispatch on the UI thread Dispatcher.BeginInvoke(() => MessageBox.Show(message));
}
}
}
Summary
Thank you for reading my first Wiki page! I hope that if your app uses Internet resources you'll use my class.
Download the sample project: File:NetworkInformationApp.zip


Hamishwillee - Well written first article on the wiki
Hi Sébastien
A very good first effort indeed - useful content, fairly well structured. I removed the Draft category - please confirm you're OK with that (ie you're not still working on this)
I have subedited for wiki style - mostly this is just using bold for filenames and Icode template to markup inline code objects. I've also improved the introduction as usually it is better to merge problem statements into a single section. Please check that I haven't removed or changed the meaning of anything - and that you're happy with the changes.
I've also renamed because even though you're trying to avoid blocking the UI I think that people are more likely to find the article with this title.
The introduction has a slight mismatch to the content/title. At the moment we explain the problem is that we want to "check the Internet connection is valid, right way to do this is to use this API is to check the Internet type, but it is synchronous. here is solution"
It might be better to say -"this is how you check the Internet connection type, but it is synchronous, one reason you might want to do this is to check whether you have a valid Internet connection". ie to reorder so that we state that checking the Internet connection is valid is one use of this trick.
I'm a beginner WP programmer, so I found the code dump of your utility a little hard to work though. I think got it in the end, but might be worth providing a few words on how it works and links to relevant classes. Just a brief overview of the architecture and answers to obvious questions like why did you use Thread rather than a Thread pool and what about the dispatcher which is mentioned but not shown. It might be that we need a generic topic for this, or at least links to topics that cover this on MSDN.
The point of this is that if I can learn a bit from your code and why you did things then I can reuse the approaches given in other similar circumstances.
More generally, I guess I'm saying a topic "How to use long running synchronous functions in Windows phone" and/or "Threading in Windows Phone" would be useful links - both for this and for topics like Dropbox_with_Windows_Phone since its a common problem. Would be nice to have a wiki topic, but only if it extends or builds over what is delivered on MSDN
Also, you call if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) - does this not prove the connection?
Hope that makes sense. I know its a bit rambling!
Thanks again for this, a useful trick, well presented.
Regards
Hamishhamishwillee 09:40, 12 September 2012 (EEST)