Will anobody be able to help me?
I am creating a windows service that connects to a sql database and checks a date in the table and compares it to todays date and up
Set Timer.AutoReset = true. otherwise it will do its work only one time. but it's better to work with threading in windows services.
[edit] ah, yes. autoreset is true in default. I put this too in my code: GC.KeepAlive( myTimer ); so the gc won't remove it if it is inactive.
Another way of doing this would be to wait on an event rather then using a timer.
i.e.
public class PollingService
{
private Thread _workerThread;
private AutoResetEvent _finished;
private const int _timeout = 60*1000;
public void StartPolling()
{
_workerThread = new Thread(Poll);
_finished = new AutoResetEvent(false);
_workerThread.Start();
}
private void Poll()
{
while (!_finished.WaitOne(_timeout))
{
//do the task
}
}
public void StopPolling()
{
_finished.Set();
_workerThread.Join();
}
}
In your Service
public partial class Service1 : ServiceBase
{
private readonly PollingService _pollingService = new PollingService();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_pollingService.StartPolling();
}
protected override void OnStop()
{
_pollingService.StopPolling();
}
}