The `IDisposable` pattern and its correct usage often are the subject of flaming discussions. At least among those developers, who are aware of its existence. Oh, sorry. Truth be told, the pattern had been the subject of discussions, but after the exciting and extremely detailed article on the topic was published by fathers of .NET, CLR, etc., the only thing left for us was to follow their wise recommendations.
And so did I, because `NetMonitor.PingService` uses `Threading.Timer` & `NetworkInformation.Ping` types which implement `IDisposable` by themselves. Here is how the canonic `IDisposable` implementation looks like, applying for `PingService` class:
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (isDisposed) return; if (!disposing) return; if (IsRunning) Stop(); if (timer != null) timer.Dispose(); if (ping != null) ping.Dispose(); isDisposed = true; } ~PingService() { Dispose(false); }
Note the presence of a finalizer, 2 working modes of Dispose method, etc. All this stuff is explained with uncompromising details in the above-mentioned article. Great reading, don’t miss it.