I just found out about a locked class and that it should be faster than just locking. Now this is all good and good, but I wonder how to implement it.
As far as I know, the only way to guarantee that an operation on a variable is atomic is to ensure that only one thread can access this variable at any given time. This is a lock.
I used a reflector to get the lock source, but it seems like it uses an external method to do all its work:
[MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern int ExchangeAdd(ref int location1, int value);
I ran a few tests, and actually locking is twice as fast as just locking the object and increasing it.
How do they do it?
source share