Skip to content

Instantly share code, notes, and snippets.

@Tamschi
Created November 29, 2018 17:20
Show Gist options
  • Save Tamschi/3d0476e838c5ab79896a23f728f301d3 to your computer and use it in GitHub Desktop.
Save Tamschi/3d0476e838c5ab79896a23f728f301d3 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
struct InterlockingLock : IDisposable
{
object _lock;
public InterlockingLock(object @lock)
{
_lock = @lock;
bool lockWasTaken = false;
try { Monitor.Enter(_lock, ref lockWasTaken); }
catch { if (lockWasTaken) Monitor.Exit(_lock); throw; }
}
public void Transfer(object @new)
{
bool lockWasTaken = false;
try { Monitor.Enter(@new, ref lockWasTaken); }
catch { if (lockWasTaken) Monitor.Exit(@new); throw; }
var old = _lock;
_lock = @new;
Monitor.Exit(old);
}
public void Dispose() => Monitor.Exit(_lock);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment