Created
June 21, 2015 22:43
-
-
Save NickStrupat/1e101014f6218737279b to your computer and use it in GitHub Desktop.
Instance Re-entrancy Guard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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