Are variables used by System.Threading.Timer subject to caching?

106 views Asked by At

I'm trying to troubleshoot a process that is mysteriously stopping, and I'm trying to determine if we could have an issue with a variable getting cached and never read again.

In my scenario, I have an operation that occurs on a timer (I'll call that Poll) and a pair of outside functions that get called to signal the start and stop of an external operation. Due to details not really worth going into, this hypothetical class does not want the Poll operation to execute if the external operation is taking place. Additionally, the external operation could occur multiple times simultaneously, so I'm using a counter to indicate the number of operations in progress.

The current logic looks more or less like this simplified example:

class MyClass
{
    private int operationsInProgress;

    private void Poll() // Pretend we have a timer in place that's calling this periodically
    {
        var inProgress = operationsInProgress;

        if (inProgress > 0) return;

        DoSomething();
    }

    public void StartExternalOperation()
    {
        Interlocked.Increment(ref operationsInProgress);
    }

    public void EndExternalOperation()
    {
        Interlocked.Decrement(ref operationsInProgress);
    }
}

Assumptions:

  • Both StartExternalOperation and EndExternalOperation are being called the same number of times--they're executed within a try...finally and there is no path that leaves an orphaned Start sitting out there
  • At some point after an indeterminate number of executions, DoSomething() never gets called again. In my real scenario, I don't know exactly why, but I have eliminated all other causes that I can find other than this one.

Is it possible because I'm not using any kind of fence (either through Interlocked or a volatile variable) on the read operation that the value is getting cached and the actual variable isn't getting read again?

Since this is an issue that we can't reliably reproduce, I need to know if what I'm suspecting could reasonably be the cause. I could change the code to use something more formal like a ReaderWriterLock (or Slim) and I know I would have proper logic, I just need to know if what I've described could legitimately be the cause.

0

There are 0 answers