Skip to content

Instantly share code, notes, and snippets.

Last active June 12, 2016 01:59
Show Gist options
  • Select an option

  • Save anonymous/78401252273d49e00ed27358772f445a to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/78401252273d49e00ed27358772f445a to your computer and use it in GitHub Desktop.
public class SyncDictionary : Dictionary<object, object>
{
private volatile int version;
private volatile bool isWriterInProgress;
public new object this[object key]
{
get
{
object value;
int currentversion;
int spinCount = 0;
do
{
currentversion = version;
TryGetValue(key, out value);
if ((++spinCount) % 8 == 0)
{
Thread.Sleep(1);
}
} while (isWriterInProgress || (currentversion != version));
return value;
}
set
{
isWriterInProgress = true;
base[key] = value;
Interlocked.Increment(ref version);
isWriterInProgress = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment