using System.Threading; public class WebCrawler { private Timer mTimer; public void Start() { mTimer = new Timer(OnTimerTicked, null, 0, 100); } public void Stop() { mTimer.Change(Timeout.Infinite, Timeout.Infinite); } private void OnTimerTicked(object state) { DoSomethingLong(); } }
The problem is the operation implemented in OnTimerTicked may take more than the timer interval (which is 100 milliseconds in the above example) to run. This is not desired as it may lead to memory corruption. The simple way to work around this is to fire the timer only once at the start, which will then invoke OnTimerTicked callback function, at the end of the OnTimerTicked callback, the timer can be reinvoked by calling its change() method, until flag change which cancel the timer's ticked operation. This is shown in the following code.
using System.Threading; public class WebCrawler { private Timer mTimer; private bool mIsWorking; public void Start() { mIsWorking=true; mTimer = new Timer(OnTimerTicked, null, 0, 100); } public void Stop() { mIsWorking = false; mTimer.Change(Timeout.Infinite, Timeout.Infinite); } private void OnTimerTicked(object state) { if(mIsWorking) { DoSomethingLong(); mTimer.Change(100, Timeout.Infinite); } } }
No comments:
Post a Comment