I am trying to implement the following functionality:
class WeightResolver {
WeightMonitor _source;
bool _cancelled;
Weight _threshold;
public Cancel() {
_cancelled = true;
}
public Weight Resolve(){
_cancelled = false;
while(_source.CurrentWeight < threshold ) {
if(_cancelled)
throw new CancelledOperationException();
// Wait until one of the above conditions is met
}
return _source.CurrentWeight
}
}
However I am running into trouble managing my threads. For example, the Cancel method is registered via an event and Resolve invoked as follows:
_activity_timeout_manager.TimeoutHandler += new Action(_weight_resolver.Cancel())l
try {
var weight = _weight_resolver.Resolve();
}
catch(CancelledOperationException) { .... }
where the activity manager is running a timer on tick of which it invokes events using TimeoutHandler.Invoke();
The problem is that even though it is properly registered with the event, Cancel() never gets called. I believe this is because the thread it is calling to is currently spinning and therefore it never gets a chance at the CPU.
What can I do to remedy the situation short of making the call to Resolve() asynchronous? It is extremely preferable for WeightResolver.Resolve() to stay synchronous because the code calling it should spin unless some return is provided anyways.
EDIT: To clarify what I'm asking for. This seems like a fairly common set-up and I would be surprised if there isn't a simple standard way to handle it. I simply have never run across the situation before and don't know what exactly it could be.