Hi all,
I want to make multiple instances of this class.
public class Worker
{
private object _lockObject;
private Thread _workerThread;
private string _name;
public Worker(object lockObject, string name)
{
_name = name;
_lockObject = lockObject;
_workerThread = new Thread(new ThreadStart(DoWork));
_workerThread.Start();
}
private void DoWork()
{
while(true)
{
lock(_lockObject)
{
Console.WriteLine(_name + "Doing Work");
}
}
}
}
If I pass the same lock object to multiple instances of the class, will a lock in one class instance result in the other class instance waiting on that lock to be free?
static void Main()
{
private readonly object sharedLockObject = new object();
Worker a = new Worker(sharedLockObject,"a");
Worker b = new Worker(sharedLockObject,"b");
Console.ReadLine();
}
I think that in the above case, Workers will never be : Console.WriteLine(_name + "Doing Work"); at the same time?
I just would like some confirmation, as I am unsure as to whether the lock() will lock the reference, or the object that is referenced.
Thanks!