0

I'm creating a C# library that will implement an EventHandler that notifies it's listeners when the computer network connection changes, it has two states --connected and not connected.

Given my requirements, I believe I need a global variable in my library that stores the "connected" boolean value and a continual loop that constantly checks for internet connection, comparing the result of that check with my global boolean.

Should I do an async loop method with locking around my global boolean? Is there any set design pattern that I could use? Please point me in the right direction as I'm relatively new to asynchronous patterns and design principles, examples would be helpful.

Note: I'm also potentially restricted to .NET 4.0, so useful things like Task.Delay might not be available.

CODe
  • 2,253
  • 6
  • 36
  • 65

1 Answers1

1

Such an event handler already exists, for physical network connectivity. See Event to Detect Network Change (stackoverflow.com)

However, if you would like to do it yourself, or want to check for other conditions (like internet access) you could implement it thus:

    public static bool IsConnected { get; protected set; }
    protected readonly static object _sync = new object();
    protected static Task NetworkTask;

    public static void Start(int period = 1000)
    {
        NetworkTask = Task.Run(() =>
            {
                lock (_sync)
                {
                    IsConnected = MyNetworkManager.IsConnected();
                    System.Threading.Thread.Sleep(period);
                }
            });
    }

Please note you cannot lock a boolean directly, since it is a value type, but you can create a readonly object to act as a proxy for the lock.

Community
  • 1
  • 1
  • I have seen the EventHandlers that exist to do this, but I'm tasked with writing my own. Thank you for the implementation though, this is how I envisioned doing it myself. – CODe Oct 16 '15 at 20:16