Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Timer vs Thread in Service

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 interval the service will get the same data twice.

The effect i´m trying to achieve(Just for visualization):

while(true)
{
    if(Getnrofrows() > 0)
      do stuff
    else
      sleep for 10 sec
}

Ppl saying Thread.Sleep is a bad idea in production services, how do I do this with timers?

/mike

like image 602
Mike Ribeiro Avatar asked Aug 13 '10 07:08

Mike Ribeiro


2 Answers

Did you try to set Timer property auto reset to false, and enabling timer again when process of refreshing data is over

using System;

public class PortChat
{
    public static System.Timers.Timer _timer;
    public static void Main()
    {

        _timer = new System.Timers.Timer();
        _timer.AutoReset = false;
        _timer.Interval = 100;
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
        _timer.Enabled = true;
        Console.ReadKey();
    }

    static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //Do database refresh
        _timer.Enabled = true;
    }
}
like image 126
adopilot Avatar answered Nov 04 '22 03:11

adopilot


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

    }
}
like image 39
jgauffin Avatar answered Nov 04 '22 01:11

jgauffin