How to properly synchronize this? At the moment it is possible thatSetData is called after e.WaitOne() has completed so d could be already set to another value. I tried to insert locks but it resulted into a deadlock.
AutoResetEvent e = new AutoResetEvent(false);
public SetData(MyData d)
{
this.d=d;
e.Set(); // notify that new data is available
}
void Runner() // this runs in separate thread and waits for d to be set to a new value
{
while (true)
{
e.WaitOne(); // waits for new data to process
DoLongOperationWith_d(d);
}
}
Will the best solution be to introduce a new boolean variable "dataAlreadyBeenSetAndWaitingToBeProcessed" that is set in setdata to true and at the end of DoLongOperationWith it could be set to true, so if SetData is called with this variable set to true it could just return?