.net Lock - Two questions

Two questions about Lock () in .net

Firstly, I know that if an object is locked inside one class and another class tries to lock the same object, this causes a dead end. But why? I read about it on MSDN, but MSDN is rarely all clear.

---- Edit Question One ---- Still confused. I have a main thread (UI thread) that generates many Threadpool threads. Each child stream blocks data before it works with it. It works great every time.

If I then try to block the same data from the user interface thread to check if I should even worry about creating a new thread for the edge case, I create a deadlock almost every time.

---- Change the second question ---- Secondly, if I have a complex object that I am blocking, are all child objects inside it locked too? Demo version:

internal sealed class Update
{
    //Three objects instantiated via other external assemblies
    public DataObject One { get; set; }
    public DataObject Two { get; set; }
    public ReplayStatus Status { get; set; }
}

If I call lock (UpdateObject), are each of the three internal objects and all child objects also locked?

Therefore, I should do something like this to prevent playback streams with my data objects:

Lock(UpdateObject.One)
{
    Lock(UpdateObject.Two)
    {
        Lock(UpdateObject.Status)
        {
            //Do Stuff
        }
    }
} 
+3
source share
2 answers

-, , . , , . , , , () , ( ). , , - , , , .

-, lock #, "" . "" ( ). - , , . , , - .

+3

-, , , , .

. , , , .

- -:

1. thread1 locks instanceA
2. thread2 locks instanceB
3. thread1 attempts to lock instanceB and now must wait on thread2
4. thread2 attempts to lock instanceA and now must wait on thread1

, . .

lock (UpdateObject), ?

, "" . . , .

+5

All Articles