I have several threads which call a method. It looks something like this:
public void DoWork(params int[] initialConditions)
{
//Do a lot of work
}
However, If conditions are changing quickly, I get a lot of stale intermediate results because I can't finish the calculations quickly enough. I know! I'll modify the code to look like this:
public void DoWork(params int[] initialConditions)
{
if(Monitor.TryEnter(syncLock)
{
//Do a lot of work
Monitor.Exit(syncLock);
}
}
Now I won't bother to do calculations unless my previous calculations are finished. I'll be a little behind in rapidly changing situations, but no more than I would have been, and I won't waste my time doing all that extra work for stale results.
However,
Once the situation stops changing, I'm still a little bit out of date, and the final thread that wanted to call DoWork is long gone. Is there a way to tell a thread:
if no one is doing work
do work
else
wait to do work until after the other thread finishes
but
if a new thread arrives before you start doing work, leave without doing work.
This code should meet your requirements described by pseudo code:
Interlocked.Increment
guarantees that every thread has its own priority and the latest thread has a priority that allows to executeDoWork
when it is available.