This was one of the requirements to periodically check if the internet connection for a system is on / off. Based on the Internet Connectivity Status, it will do certain actions. How do I check the Internet Connection Status periodically and asynchronously?
To solve this programming puzzle (in C#.NET), I have used System.Timers.Timer class. There was one more class available in the .NET framework, that was, System.Threading.Timer. I have chosen System.Timers.Timer class, because it is thread-safe but System.Threading.Timer class isn't out of the box.
Step 1: Created an elapsed event handler for the timer class:
<Code>
m_Timer.Elapsed += checkInternetConnectionState;
m_Timer.Enabled = true;
</Code>
Step 2: Created checkInternetConnectionState async method definition:
<Code>
{
List<string>? connectDetails = await GetConnectionDetailsAsync();
}
</Code>
Step 3: Defined GetConnectionDetailsAsync as below:
<Code>
{
List<string>? connectionDetails = null;
return Task.Run(() => {
if ((Microsoft.WindowsAPICodePack.Net.
{
NetworkCollection netCollection =
connectionDetails = new List<string>();
foreach (Network net in netCollection)
{
if (net.IsConnected)
{
connectionDetails.Add(net.Name);
connectionDetails.Add(net.Category.ToString());
connectionDetails.Add(net.DomainType.ToString());
connectionDetails.Add(net.ConnectedTime.ToString());
}
}
}
return connectionDetails;
});
}
</Code>
I have used WindowsAPICodePack to get internet connectivity status and details. If we stitch these three steps together we can achieve the desired goal.
Comments