Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created June 21, 2015 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/1e101014f6218737279b to your computer and use it in GitHub Desktop.
Save NickStrupat/1e101014f6218737279b to your computer and use it in GitHub Desktop.
Instance Re-entrancy Guard
using System;
using System.Runtime.CompilerServices;
internal class InstanceReEntrancyGuard : IDisposable {
private class Ref<T> where T : struct { public T Value { get; set; } }
private static readonly ConditionalWeakTable<Object, Ref<Boolean>> reEntranceEphemerons = new ConditionalWeakTable<Object, Ref<Boolean>>();
private readonly Ref<Boolean> hasEnteredOnce;
public InstanceReEntrancyGuard(Object instance, String reEntrantMessage = null) {
hasEnteredOnce = reEntranceEphemerons.GetValue(instance, x => new Ref<Boolean>());
if (hasEnteredOnce.Value)
throw new InvalidOperationException((hasEnteredOnce.Value ? "Re-entrance detected." : null) + (String.IsNullOrWhiteSpace(reEntrantMessage) ? null : (" " + reEntrantMessage)));
hasEnteredOnce.Value = true;
}
public void Dispose() {
hasEnteredOnce.Value = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment