Is the lock instance or member

I have a question about locking in C #. C # blocks an instance of an object or member.

If I have the following code:

lock(testVar)
{
    testVar = testVar.Where(Item => Item.Value == 1).ToList();
    //... do some more stuff
}

Does C # keep the lock, even I set it testVarto a new value?

+4
source share
3 answers

All C # objects inherit from System.Object, which itself always contains 4 bytes, intended for use when using syntactic sugar for lock. This is called a SyncBlock object.

new, ToList, List<T>, , lock. , lock. try-finally , .

readonly, sync . , , .

Edit:

MSDN, :

SyncTableEntry SyncBlock, , . , -, thunking AppDomain. , SyncBlock syncblk . , lock (obj) obj.GetHashCode.

Object in memory representation

+7

, (testVar). , , .

: - lock readonly. testVar ... , RemoveAll . , , , lock.

, . , .

+4

lock try/finally, Monitor.Enter/Monitor.Exit. , ( VS2015 Preview), , .

var testVar = new List<int>();
lock (testVar)
{
    testVar = new List<int>();
    testVar.Add(1);
}

:

List<int> list2;
List<int> list = new List<int>();
bool lockTaken = false;
try
{
    list2 = list;
    Monitor.Enter(list2, ref lockTaken);
    list = new List<int> { 1 };
}
finally
{
    if (lockTaken)
    {
        Monitor.Exit(list2);
    }
}

, , testVar , list list2. :

  • list2 list, List<int>.
  • Monitor.Enter(list2, ref lockTaken) List<int> .
  • list List<int>, list2 , .
  • list2

, , , . , , .

+1

Source: https://habr.com/ru/post/1570854/


All Articles