Monday, February 07, 2005

Locking for Synchronization

If you have a scenario where a piece of code/resource is called/accessed by more than one execution sequences (threads for example) asynchronously, and you want the target piece of code/resource to be exclusively available to one caller/accessor at a time then lock statement in C# is the right tool for you.

Recently we were facing a similar issue in our Replication/Warehousing service where the timeout event of timer control was spawning new calls to code while the previous call has not finished executing. This was a problem because we were loosing the maintained states and transactions were not being processed, since connections were already listed in transactions (in previous call i.e.). What we did to resolve this issue is that we enclosed our critical code in lock and synchronization was guaranteed !

Here is the code snippet we used:


lock(this)
{
if ( System.DateTime.Now.Hour >= 0 && System.DateTime.Now.Hour < 9)
{
if ( System.DateTime.Now.Day.ToString() != "Monday" )
{
RepSer.ControlProcessor.ServiceMain();
}
}
}

No comments: