What happens if I lock an object while another thread use that variable?
c#, locking, multithreading
Solution
lock keyword doesn't "lock" or "freeze" target object (in a sense preventing from changes).
lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released.
So in your case it won't prevent other threads from enumerating the list.
Problem
I am not sure how lock works. What happens if I have a `List<T> list` and 2 threads ? What happens if thread1 start running first and enumerate that list ``` foreach(T t in list) { // code } ``` and in the same time, but after thread1 has started, thread2 will lock the list ``` lock(list) { // code } ``` I use `ThreadPool` do to some processing and I need to know how lock really works and if is thread safe ``` ThreadPool.QueueUserWorkItem(new WaitCallback(method), obj); ```