junwei's profileRichard's footprint on ....PhotosBlogListsMore Tools Help

Blog


    May 30

    System.Threading.Timer

    In one of our system, there is a task which demands to check the incoming mail task periodically and send it out if any. Since it is a sole task, no need to much communicated heavily between threads, just scan the database mail table to pull out these task and send. Compared the currently existing three different APIs in .NET, one is mainly for windows form application, one is for accurate and complex server multiplethread application, and the third one is the lightweight timer for simple thread task, it is System.Threading.Timer. I chose the last one as my solution. Here I put the  presudo codes for further reference.
     
    System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(WorkerClass.ExecuteMailTask));
    timer.Change(1000,0); // specify start timer after 1 second
     
    ...
    in my WorkerClass, I define one static method ExecuteMailTask to stop timer temporarily and execute the mail task. the following is the preseudo codes
     
    ExecuteMailTask(object state)
    {
       Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +"mail monitor task is running on thread #"+Thread.CurrentThread.ManagedThreadId);
       System.Threading.Timer t = (System.Threading.Timer)state;
       t.Change(Timeout.Infinite, Timeout.Infinite);// first stop the timer teporarily
       ... // necessary codes to pull out mail data
       t.Change(0,20000); //restart the timer
    }
     
    I have omitted the exeption handling codes, in a product enviroment, wrap above codes in a try ...catch.. finally block will be an apropriate choice when robustness is considered.