May 11, 2006

Using A System.Threading.Timer To Implement A TimeOut Feature

// The Timer delegate to be invoked on a callback (from 
// another thread)
protected void TimeOut(object obj)
{
  lock(accesslock) // Careful. TimeOut callback occurs on 
another thread { log.Error("Something TIMED OUT, will take action"); TakeTimeOutAction(); } } ... // Example usage using (Timer timer = new Timer(new TimerCallback(TimeOut), null,
10000L, Timeout.Infinite)) { while (!complete) { log.Debug("Something waiting for something else to complete"); Thread.Sleep(1000); } }

No comments: