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

时间:2016-05-11 14:02:38

标签: c# connectivity propertychanged

我的应用程序使用互联网,所以我想检查,如果有互联网连接,如果没有 - 显示错误。 我已经实现了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事件仅在互联网连接发生变化时启动,但我现在还需要,如果开头有互联网连接。有没有办法解决这个问题而不重复代码而不是将每个代码都写成单独的方法?

1 个答案:

答案 0 :(得分:1)

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

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

然后当程序启动时执行

DoStuffDependingOnConnection(Network.IsConnected);

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

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