Skip to content

Instantly share code, notes, and snippets.

@neuecc
Created August 4, 2021 01:47
Show Gist options
  • Select an option

  • Save neuecc/1dff9516cb23a5bd233e252d0261bfe4 to your computer and use it in GitHub Desktop.

Select an option

Save neuecc/1dff9516cb23a5bd233e252d0261bfe4 to your computer and use it in GitHub Desktop.
public class SynchronizedEnumerator<T> : IEnumerator<T>
{
bool isDisposed;
readonly object gate;
readonly bool lockTaken;
readonly IEnumerator<T> enumerator;
public SynchronizedEnumerator(object gate, IEnumerator<T> enumerator)
{
this.gate = gate;
this.enumerator = enumerator;
Monitor.Enter(gate, ref lockTaken);
}
public T Current => enumerator.Current;
object IEnumerator.Current => Current!;
public bool MoveNext() => enumerator.MoveNext();
public void Reset() => enumerator.Reset();
public void Dispose()
{
if (!isDisposed)
{
isDisposed = true;
try
{
enumerator.Dispose();
}
finally
{
if (lockTaken)
{
Monitor.Exit(gate);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment