I have a class Library Application Called API. Inside which I have a method called SynchronizeMe.
public class APIClass
{
object baton = new object();
static int count = 0;
public void SynchronizeMe()
{
while(true)
{
lock (baton)
{
int temp = count;
Thread.Sleep(5000);
count = temp + 1;
Console.WriteLine("Thread Id " + Thread.CurrentThread.ManagedThreadId + " Name:" + Thread.CurrentThread.Name + " incremented count to " + count);
}
Thread.Sleep(1000);
}
}
}
I have two console Application Thread1 and Thread2. Both of them calling SynchronizeMe Method. Like
API.APIClass apicall = new API.APIClass();
apicall.SynchronizeMe();
When I run this I see Both of them printing count start from 1. That means it is not syncronized. Am I understanding the concept of multi threading something wrong? Or code has issue? Or Thread in same application can only be synchronized. If I want to synchronize this way what is the way?
I think both Thread1 and Thread2 has different Instance of APIClass so Synchronization not Possible. Is there some way out?