Search code examples
c#connectivitypropertychanged

Launch Changed event before anything changes


My app uses internet, so I would like to check, if there is internet connection, and if not - show error. I have implemented class as shown in 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;
        }
    }
}

But using this approach I have to duplicate my code:

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
        }
    });
};

Because InternetConnectionChanged event launches only if internet connection changes, but I also need to now, if there is internet connection at the beginning. Is there a way to that without duplicating code and not writing each code as separate method?


Solution

  • Just encapsulate your logic in its own method, something like this:

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

    Then when your program launches execute

    DoStuffDependingOnConnection(Network.IsConnected);
    

    And your event handler will look like this:

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