【问题标题】:How to detect network change events asynchronously in UWP apps如何在 UWP 应用程序中异步检测网络更改事件
【发布时间】:2021-05-31 15:27:04
【问题描述】:

我正在构建一个 UWP 应用程序,我试图在其中异步检测不同类型的网络事件更改。

用户可以在哪里进行网络更改并及时查看更改的效果。

例如-

  • 飞行模式开/关异步检测
  • 蓝牙开/关异步检测
  • 网络连接开/关异步检测

我能够使用以下代码同步检测飞行模式开/关检测

    public bool isConnectedToNetwork()
    {
        return NetworkInformation.GetInternetConnectionProfile()?.NetworkAdapter != null;
    }

    private void checkAirplaneMode()
    {
        if(isConnectedToNetwork())
        {
            airplaneText.Text = "AirplaneMode: OFF";
        } 
        else
        {
            airplaneText.Text = "AirplaneMode: ON";
        }
    }

但我想(我想)在网络事件发生变化时异步执行此操作。 因此,用户不必一次又一次地运行应用程序来查看更改。

【问题讨论】:

    标签: c# windows uwp windows-10


    【解决方案1】:

    UWP 提供了特定的事件来通知这些变化,例如 NetworkInformation.NetworkStatusChanged Event ,BluetoothDevice.ConnectionStatusChanged Event。

    如果你想检测网络变化事件,你可以register for notifications of connection state change events

    // register for network status change notifications
    networkStatusCallback = new NetworkStatusChangedEventHandler(OnNetworkStatusChange);
            if (!registeredNetworkStatusNotif)
            {
                NetworkInformation.NetworkStatusChanged += networkStatusCallback;
                registeredNetworkStatusNotif = true;
            }
    

    然后您可以retrieve the connection state change information 并添加您的触发代码。

    async void OnNetworkStatusChange(object sender)
    {
    // get the ConnectionProfile that is currently used to connect to the Internet                
            ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
    
            if (InternetConnectionProfile == null)
            {
                //add code about not connected
            }
            else
            {
                //add code about connected
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2018-04-07
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多