上次发了一个文章获取windows网络状态,判断是否可以访问互联网。传送门:获取本机网络状态
这次我们监听网络状态切换,具体代码如下:
public class WindowsNetworkHelper
{
private static Action<bool>? _NetworkStatusChangedCallback;
/// <summary>
/// 检查当前网络是否可访问互联网、并设置网络状态变更回调
/// </summary>
/// <param name="networkStatusChangedCallback"></param>
/// <returns>true-可访问互联网;false-不可访问互联网</returns>
public static bool CheckInternetAccessAndSetNetworkStatusChangedCallback(Action<bool> networkStatusChangedCallback)
{
//幅值
_NetworkStatusChangedCallback = networkStatusChangedCallback;
//注册网络状态变更事件
NetworkInformation.NetworkStatusChanged -= NetworkInformation_NetworkStatusChanged;
NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
//返回当前网络状态
return CheckInternetAccess();
}
private static void NetworkInformation_NetworkStatusChanged(object sender)
{
//网络状态变化,获取一次当前网络状态
var bInternetAccess = CheckInternetAccess();
//触发回调,把网络状态作为参数传入
_NetworkStatusChangedCallback?.Invoke(bInternetAccess);
}
public static bool CheckInternetAccess()
{
var connectProfile = NetworkInformation.GetInternetConnectionProfile();
if (null == connectProfile) return false;
var networkLevel = connectProfile.GetNetworkConnectivityLevel();
if (networkLevel == NetworkConnectivityLevel.InternetAccess)
return true;
else
return false;
}
}
调用方式:
using System;
using System.Diagnostics;
using System.Management;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Windows.Networking.Connectivity;
namespace ConsoleApp3
{
internal class Program
{
private static void Main(string[] args)
{
var ret = WindowsNetworkHelper.CheckInternetAccessAndSetNetworkStatusChangedCallback(NewtworkStatusChanged);
Console.WriteLine($"宜家网络状态是否可访问互联网:{ret}");
Console.ReadLine();
}
private static void NewtworkStatusChanged(bool sender)
{
Console.WriteLine($"当前是否可访问互联网:{sender},是否后台线程={Thread.CurrentThread.IsBackground}");
}
}
}
从联网到断开网络、再连上的效果: