C# Timer vs Thread in Service

前端 未结 4 2111
灰色年华
灰色年华 2021-02-09 05:56

I have a Service that hits a database every 10 sec and gets the data if there is any. The thing is that processing this data can take up to 30 sec. If I use a Timer with 10 sec

4条回答
  •  臣服心动
    2021-02-09 06:52

    I don't see any problems with using Sleep at all other than you might end up with ugly code.

    To answer your question:

    public class MyTest
    {
        System.Threading.Timer _timer;
    
    
        public MyTest()
        {
           _timer = new Timer(WorkMethod, 15000, 15000);
        }
    
    
        public void WorkMethod()
        {
           _timer.Change(Timeout.Infinite, Timeout.Infinite); // suspend timer
    
           // do work
    
           _timer.Change(15000, 15000); //resume
    
        }
    }
    

提交回复
热议问题