Using lock with Threading.Timer

前端 未结 2 1219
时光取名叫无心
时光取名叫无心 2020-12-24 03:57

I have a Windows Service application which uses a Threading.Timer and a TimerCallback to do some processing at particular intervals. I need to lock

2条回答
  •  青春惊慌失措
    2020-12-24 04:04

    The worst that can happen if the processing code takes more than 10s to execute is that you will be wasting 1 threadpool thread every time there's a new callback called (they will be waiting for in the lock statement). And if you take all the threadpool threads HttpWebRequest, ASP.NET, asynchronous delegate invocations... will suffer.

    What I would do is to schedule the first callback immediately. Then, if you really need your DoSomething() to be called every 10s:

    public void DoSomething ()
    {
           DateTime start = DateTime.UtcNow;
           ...
           TimeSpan elapsed = (DateTime.UtcNow - start);
           int due_in = (int) (10000 - elapsed.TotalMilliseconds);
           if (due_in < 0)
               due_in = 0;
           timer.Change (due_in, Timeout.Infinite);
    }
    

    Or something along that line.

提交回复
热议问题