public void EnterWriteLock()
{
ServerSpinWait sw = new ServerSpinWait();
do {
int state = rwlock;
if (state < RwWrite) {
if (Interlocked.CompareExchange(ref rwlock, RwWrite, state) == state)
return;
state = rwlock;
}
// We register our interest in taking the Write lock (if upgradeable it's already done)
while ((state & RwWait) == 0 && Interlocked.CompareExchange(ref rwlock, state | RwWait, state) != state)
state = rwlock;
// Before falling to sleep
while (rwlock > RwWait)
sw.SpinOnce();
} while (true);
}