I asked a question earlier on this thread Timed events overlapping during execution The answer I got didnt really work out as I expected. I modified it a little bit based on the msdn https://msdn.microsoft.com/en-us/library/system.threading.interlocked(v=vs.110).aspx article and it worked. Or so I think. Here is my modified code
public partial class Service1 : ServiceBase
{
private Timer timer1 = null;
private long isTaskRunning = 0;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1 = new Timer();
this.timer1.Interval = 1000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
Library.WriteErrorLog("service has started");
}
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Acquiring Lock");
try
{
if (Interlocked.Exchange(ref isTaskRunning, 1)==1)
{
Console.WriteLine("Lock Denied");
return;
}
else
{
Console.WriteLine("Lock Acquired");
//retrieve data from database
//read rows
//Loop through rows
//send values through network
//receive response and update db
Interlocked.Exchange(ref isTaskRunning, 0);
}
}
catch (Exception ex)
{
Library.WriteErrorLog(ex);
}
}
}
protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteErrorLog("service has stopped");
}
}
My question now is, is this code Thread-safe? And is there any possibility that this code might crash. The code is supposed to run on Virtual Private Server and is a part of business critical system. Any help would be appreciated.