I have a piece of data that takes quite a lot of time to fetch. I have different ways of figuring out if new data should be fetched or if I can use my current "cache" theResult
When someone asks for that piece of data I want to be able to both do a blocking and non blocking return.
Im not sure what the best way is to do that, I was considering something with ManualResetEventSlim and a lock:
NonBlocking:
theState = State.None;
public Data GetDataNonBlocking(){
lock(_myLock){
if (theState == State.Getting)
return null;
if (theState == State.Complete
return theData;
theState = State.Getting;
_resetEvent.Reset();
Task.Factory.StartNew(
()=>{
//<...Getting data.....>
theData= ...data....;
lock(_myLock){
theState = State.Complete;
_resetevent.Set();
}
});
return null;
}
}
Blocking:
public Data GetDataBlocking(){
lock(_myLock){
if (theState == State.Getting){
_resetevent.Wait();
return theData;
}
if (theState == State.Complete)
return theData;
_resetevent.Reset();
theState = State.Getting;
}
//.....
theData= 1234;
lock(_myLock){
State = State.Complete;
_resetevent.Set();
}
return theData;
}
But I'm not certain that is the way to do a thing like that. For example the _resetEvent.Wait()
inside a lock(...){}
?