I am looking for a class that defines a holding structure for an object. The value for this object could be set at a later time than when this container is created. It is useful to pass such a structure in lambdas or in callback functions etc.
Say:
class HoldObject<T> {
public T Value { get; set; }
public bool IsValueSet();
public void WaitUntilHasValue();
}
// and then we could use it like so ...
HoldObject<byte[]> downloadedBytes = new HoldObject<byte[]>();
DownloadBytes("http://www.stackoverflow.com", sender => downloadedBytes.Value = sender.GetBytes());
It is rather easy to define this structure, but I am trying to see if one is available in FCL. I also want this to be an efficient structure that has all needed features like thread safety, efficient waiting etc.
Any help is greatly appreciated.
Never seen a class like that, but should be pretty simple.
public class ObjectHolder<T>
{
private T value;
private ManualResetEvent waitEvent = new ManualResetEvent(false);
public T Value
{
get { return value; }
set
{
this.value = value;
ManualResetEvent evt = waitEvent;
if(evt != null)
{
evt.Set();
evt.Dispose();
evt = null;
}
}
}
public bool IsValueSet
{
get { return waitEvent == null; }
}
public void WaitUntilHasValue()
{
ManualResetEvent evt = waitEvent;
if(evt != null) evt.WaitOne();
}
}