Skip to content

Lockable

Jordan Duerksen edited this page May 15, 2018 · 6 revisions

Lockable extends LockableSlim by supporting IDisposable and adding a ValueChanged event and WaitForValueChanged method.

Note that if an onValueChanged callback is passed into the constructor, it will be called before the ValueChanged event is raised.

public class Lockable<TValue> : LockableSlim<TValue>, IDisposable
{
    //additional events
    public event ValueChangedDelegate<TValue> ValueChanged;

    //additional methods
    public bool WaitForValueChanged(int msTimeout = -1); //
    public void Dispose();
}

Use

using W;
//declare the Lockable property
protected Lockable<int> SomeInt { get;} = new Lockable<int>();
.
. //do something on another thread which will change the value of SomeInt
.
// wait the specified number of milliseconds for the value to change
if (someInt.WaitForValueChanged(5000)) //in this case, 5 seconds
{
    //do something because the value changed
}
else
{
    //do something because the value did not change
}

someInt.Dispose();

You can pass in an initial value

public Lockable<string> Username { get; } = new Lockable<string>("New User");

You can pass in an Action<object, TValue, TValue> (where TValue is the declared type) which will be called when the property's Value changes:

public Lockable<string> Username { get; } = new Lockable<string>((sender, oldValue, newValue) => { /* Do something here */ });

Or do both:

public Lockable<string> Username { get; } = new Lockable<string>("New User", (sender, oldValue, newValue) => { /* Do something here */ });

Clone this wiki locally