I'm working on a class that creates and manages multiple socket connections and which will be forwarding information received from the sockets to the main thread and vice-versa. Multi-threading where I'm passing so much information in and out is new to me (as is most things in C#), so I need a clarification on what exactly locks
do.
When I lock a section of a method does it only ensure that no other thread can enter that section of code or does it actually prevent all the variables in that section of code from being modified by other threads no matter where they occur?
For example:
public class TestLock
{
public volatile int a = 0;
public volatile int b = 2;
private object ALock = new Object();
public TestLock() { }
public void UnlockEdit(int atemp, int btemp)
{
a = atemp;
b = btemp;
}
public void LockedEdit(int atemp, int btemp)
{
lock(ALock)
{
a = atemp;
b = btemp;
}
}
public int[] ReturnValues()
{
int[] ret = new int[2];
lock (ALock)
{
ret[0] = a;
ret[1] = b;
}
return ret;
}
}
If thread A calls the LockedEdit
method and reaches the lock just slightly before thread B comes into UnlockEdit
. What happens? Will the lock prevent thread B from modifying a
and b
? And will it block? Or does the lock only apply to the one particular branch of code? Or should I apply the same lock
object (ALock
) to every single read and write method for the objects I want to modify and read from multiple threads?