The last post dealt with building the base Future class. Now we’ll build the child class used to run [Func
The basic implementation is straight forward. The class will run a delegate typed to [Func
When a value is read and written on multiple threads there are a couple of options for synchronization between threads. One of them is to use the volatile keyword for the data. This forces the CLR to read the value from memory every time and prevents caching issues between threads. Unfortunately volatile cannot be applied to an unbounded generic.
To get around this I’ve declared the value to be of type object. Whenever the value is accessed by the user of Future
In addition Future
In a perfect world WaitEmpty in Future would really be called Wait and be virtual. Future
public class Future<T> : Future
{
private Func<T> m_function;
private volatile object m_value;
public T Value
{
get { return Wait(); }
}
public Future(Func<T> function)
{
m_function = function;
}
public T Wait()
{
base.WaitEmpty();
return (T)m_value;
}
protected override void RunCore()
{
m_value = m_function();
}
}
Next time I’ll go over the implementation of Futures which return no values.