Checking the Internet connection type on Windows Phone

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.

If your application relies on a specific server you might be tempted to simply check the Internet connection by calling the server. This could result in an inaccurate error message if your server is down, since the Internet may be available.

 

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:

  1. Add the NetworkInformationUtility.cs to your project.
  2. Attach method to the event NetworkInformationUtility.GetNetworkTypeCompleted.
  3. Call NetworkInformationUtility.GetNetworkTypeAsync(3000 /*timeout in ms*/);
  4. 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));
}
}
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.