Skip to content

Instantly share code, notes, and snippets.

@IntelOrca
Last active November 25, 2016 13:58
Show Gist options
  • Save IntelOrca/94f4204ccf2d6e0b09ef to your computer and use it in GitHub Desktop.
Save IntelOrca/94f4204ccf2d6e0b09ef to your computer and use it in GitHub Desktop.
C# Lockable class to keep the object to lock and its sync object that is actually locked together.
/// <summary>
/// Class to keep an object to lock and its sync object that is actually locked together.
/// </summary>
/// <example>
/// Lockable<List<int>> someList = new Lockable<List<int>>(new List<int>());
/// lock (someList.Sync) {
/// List<int> list = someList;
/// list.Add(2);
/// list.Add(5);
/// list.Add(9);
/// }
/// </example>
sealed class Lockable<T> where T : class
{
private readonly T _instance;
private readonly object _sync;
public Lockable(T instance)
{
_instance = instance;
_sync = new object();
}
public static implicit operator T(Lockable<T> lockable) { return lockable.Instance; }
public T Instance { get { return _instance; } }
public object Sync { get { return _sync; } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment