My application was having some issue and I found out "lock" was causing the problem. I have simplified the issue into smaller code, could be more smaller. But this will do.
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
longProcessTimer = new System.Timers.Timer(3000);
longProcessTimer.Elapsed += LongProcessElapsed;
longProcessTimer.Start();
SomeClass.Current.Start();
}
System.Timers.Timer longProcessTimer;
static string LockingString = "TestString";
private void LongProcessElapsed(object sender, EventArgs e)
{
Debug.WriteLine("Long Process Started");
lock (LockingString)//this lock will block the sublock
{
longProcessTimer.Stop();
Thread.Sleep(10000);//just for demo
longProcessTimer.Start();
}
Debug.WriteLine("Long Process Ended");
}
}
public class SomeClass
{
public static readonly SomeClass Current = new SomeClass();
System.Timers.Timer SubTimer;
Stopwatch stopWatch = new Stopwatch();
protected string SubLockingString = "TestString";
public SomeClass()
{
SubTimer = new System.Timers.Timer(500);
SubTimer.Elapsed += SubTimerElapsed;
}
public void Start()
{
stopWatch.Start();
SubTimer.Start();
}
private void SubTimerElapsed(object sender, EventArgs e)
{
SubTimer.Stop();
stopWatch.Restart();
lock (SubLockingString)
{
Debug.WriteLine("Inside sub lock, " + stopWatch.Elapsed);
}
SubTimer.Start();
}
}
Now if LockingString is locked, it will also lock SubLockingString. But if I change the value of any string, the locks wont interfere with each other.
I know the solution, but I'm just curious why is it happening ?