Last active
August 28, 2020 01:22
-
-
Save astrellon/45181998530061de3c04e3ec80e77822 to your computer and use it in GitHub Desktop.
A lock object wrapper.
This file contains hidden or 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.Threading; | |
namespace MyNamespace | |
{ | |
public class LockObject<T> : IDisposable | |
{ | |
#region Fields | |
private readonly T obj; | |
private readonly object lockObject; | |
private bool lockWasTaken; | |
#endregion | |
#region Constructor | |
public LockObject(T obj) : this(obj, obj) { } | |
public LockObject(object lockObject, T obj) | |
{ | |
this.obj = obj; | |
this.lockObject = lockObject; | |
try | |
{ | |
Monitor.Enter(this.lockObject, ref this.lockWasTaken); | |
} | |
catch (Exception) | |
{ | |
if (this.lockWasTaken) | |
{ | |
this.lockWasTaken = false; | |
Monitor.Exit(this.lockObject); | |
} | |
} | |
} | |
#endregion | |
#region Methods | |
public void Dispose() | |
{ | |
if (this.lockWasTaken) | |
{ | |
this.lockWasTaken = false; | |
Monitor.Exit(this.lockObject); | |
} | |
} | |
public bool TryGet(out T result) | |
{ | |
if (this.lockWasTaken) | |
{ | |
result = this.obj; | |
return true; | |
} | |
result = default(T); | |
return false; | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment