Hs2lib-0.4.8: Includes/FFI/LockedValue.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace WinDll.Utils
{
/// <summary>
/// A class to control access to a particulair value, Threadsafe
/// </summary>
public class LockedValue<T> : IDisposable
{
private T value;
private Semaphore sem;
/// <summary>
/// Create a new LockedValue and allow only 1 thing to access it at a time
/// </summary>
/// <param name="value">The value to monitor</param>
public LockedValue(T value):this(value, 1){
}
/// <summary>
/// Create a new LockedValue and allow @max@ things to access it at a time
/// </summary>
/// <param name="value">The value to monitor</param>
/// <param name="max"></param>
public LockedValue(T value, int max)
{
this.value = value;
this.sem = new Semaphore(max, 10, "LockedValue" + this.GetHashCode());
}
/// <summary>
/// Retreive the LockedValue
/// </summary>
/// <returns>LockedValue</returns>
public T pull()
{
this.sem.WaitOne();
return this.value;
}
/// <summary>
/// Release the LockedValue
/// </summary>
public void pulse()
{
this.sem.Release();
}
/// <summary>
/// Unsafe retreiving of the value. This should not be used under normal conditions!
/// </summary>
/// <returns>LockedValue</returns>
public T unsafePull()
{
return this.value;
}
public void Dispose()
{
this.sem.Close();
}
}
}