Skip to main content

Posts

Showing posts with the label Repeated function call

Periodically run a method without freezing UI.

 This was one of the requirements to periodically check if the internet connection for a system is on / off. Based on the Internet Connectivity Status, it will do certain actions. How do I check the Internet Connection Status periodically and asynchronously?  To solve this programming puzzle (in C#.NET ), I have used System.Timers.Timer class. There was one more class available in the .NET framework, that was, System.Threading.Timer. I have chosen System.Timers.Timer class, because it is thread-safe but System.Threading.Timer class isn't out of the box. Step 1: Created an elapsed event handler for the timer class: <Code> // Create a timer with 10 seconds interval in the init method of the form application; m_Timer = new System.Timers.Timer(10 * 1000); /* It's going to fire the below-highlighted method every 10 seconds*/ m_Timer.Elapsed += checkInternetConnectionState ;  m_Timer.Enabled = true; </Code> Step 2: Created  checkInternetConnectionState  async method defin