在任何更改之前启动 Changed 事件

Launch Changed event before anything changes

我的应用程序使用互联网,所以我想检查是否有互联网连接,如果没有 - 显示错误。 我已经实现了 class,如 this site:

所示
public class InternetConnectionChangedEventArgs : EventArgs
{
    public InternetConnectionChangedEventArgs(bool isConnected)
    {
        this.isConnected = isConnected;
    }

    private bool isConnected;
    public bool IsConnected
    {
        get { return isConnected; }
    }
}

public static class Network
{
    public static event EventHandler<InternetConnectionChangedEventArgs>
        InternetConnectionChanged;

    static Network()
    {
        NetworkInformation.NetworkStatusChanged += (s) =>
        {
            if (InternetConnectionChanged != null)
            {
                var arg = new InternetConnectionChangedEventArgs(IsConnected);
                InternetConnectionChanged(null, arg);
            }
        };
    }

    public static bool IsConnected
    {
        get
        {
            var profile = NetworkInformation.GetInternetConnectionProfile();
            var isConnected = (profile != null
                && profile.GetNetworkConnectivityLevel() ==
                NetworkConnectivityLevel.InternetAccess);
            return isConnected;
        }
    }
}

但是使用这种方法我必须复制我的代码:

if(Network.IsConnected)
{
    //do stuff with internet
}
else
    //show error message

Network.InternetConnectionChanged += async (s, args) =>
{
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
    {
        if (args.IsConnected)
        {
            //do the same stuff with internet
        }
        else
        {
            //show the same error message
        }
    });
};

因为 InternetConnectionChanged 事件仅在互联网连接发生变化时启动,但我现在也需要,如果开始时有互联网连接的话。有没有一种方法可以做到这一点而无需复制代码并且无需将每个代码都编写为单独的方法?

只需将您的逻辑封装在其自己的方法中,如下所示:

private void DoStuffDependingOnConnection(bool isConnected)
{
   if (isConnected)
   {
      //...
   }
   else /* ... */
}

然后当你的程序启动时执行

DoStuffDependingOnConnection(Network.IsConnected);

您的事件处理程序将如下所示:

await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, 
                          async () => DoStuffDependingOnConnection(args.IsConnected));