What happens if I lock an object while another thread is using this variable?

I'm not sure how locking works.
What happens if I have a List<T> list and 2 threads?
What happens if thread1 starts working first and lists this list

 foreach(T t in list) { // code } 

and at the same time, but after thread1 has started, thread2 will block the list

 lock(list) { // code } 

I use ThreadPool for some processing, and I need to know how the lock works, and if it is thread safe

 ThreadPool.QueueUserWorkItem(new WaitCallback(method), obj); 
+4
source share
3 answers

the lock keyword does not block or lock the target (in the sense of preventing changes).

Lock

ensures that one thread does not enter the critical section of the code, and the other thread is in the critical section. If another thread tries to enter a blocked code, it will wait, block, until the object is released.

So, in your case, this will not prevent other threads from listing the list.

+5
source

In the code, as it is written - the enumerator will continue to move. The point about lock is that all of your code must agree. If you used:

 lock(list) { foreach(T t in list) { // code } } 

Then, when your other thread tries to get a lock, it will queue for the first - waiting for the first thread to release the lock (either exit lock ( Monitor.Exit ) or call Monitor.Wait ).

+5
source

Locking is not magic, and must be used together. If I want the changes of some mutable object to not accidentally fall or be damaged by several threads, then I need to make sure that I only make changes to the object in the lock block.

The only thing that provides blocking is that any other code that is blocked on the same object does not work on other threads simultaneously, it is just syntactic sugar for receiving and issuing a mutex.

 lock(x) // acquire mutex associated with x, or wait until it becomes available { // do stuff } // release mutex associated with x 

Edit: MSDN lock details () are very important for anyone interested.

+1
source

All Articles