using System.Collections.Concurrent;
namespace LLama.Web.Async
{
///
/// Creates a async/thread-safe guard helper
///
///
public class AsyncGuard : AsyncGuard
{
private readonly byte _key;
private readonly ConcurrentDictionary _lockData;
///
/// Initializes a new instance of the class.
///
public AsyncGuard()
{
_key = 0;
_lockData = new ConcurrentDictionary();
}
///
/// Guards this instance.
///
/// true if able to enter an guard, false if already guarded
public bool Guard()
{
return _lockData.TryAdd(_key, true);
}
///
/// Releases the guard.
///
///
public bool Release()
{
return _lockData.TryRemove(_key, out _);
}
///
/// Determines whether this instance is guarded.
///
///
/// true if this instance is guarded; otherwise, false.
///
public bool IsGuarded()
{
return _lockData.ContainsKey(_key);
}
}
public class AsyncGuard
{
private readonly ConcurrentDictionary _lockData;
///
/// Initializes a new instance of the class.
///
public AsyncGuard()
{
_lockData = new ConcurrentDictionary();
}
///
/// Guards the specified value.
///
/// The value.
/// true if able to enter a guard for this value, false if this value is already guarded
public bool Guard(T value)
{
return _lockData.TryAdd(value, true);
}
///
/// Releases the guard on the specified value.
///
/// The value.
///
public bool Release(T value)
{
return _lockData.TryRemove(value, out _);
}
///
/// Determines whether the specified value is guarded.
///
/// The value.
///
/// true if the specified value is guarded; otherwise, false.
///
public bool IsGuarded(T value)
{
return _lockData.ContainsKey(value);
}
}
}