views:

203

answers:

1

Probably a rookie error, but i'm getting something strange. i'm trying to weave a .NET performance counter into an application.

When i call the incrementBy(value) method on my avg performance counter it is changing the RawValue of my base counter by value as well. i checked the variable names and think everything is correct.

Then when i call increment() on my base counter it adds 1 to the rawvalue of the avgcounter as well as incrementing the base counter... adding insult to injury!

Has anyone else seen this kind of behavior? Any suggestions for what's going on and how to fix it?

In code i'm using two different counters to measure the time a merge sort i wrote takes. i have a instantaneous counter for the elapsed time of the sort and an average counter.

Dim timePiece As New Stopwatch()

timePiece.Start()
MergeSort()
timePiece.Stop()

ElapsedCounter.RawValue = timePiece.ElapsedMilliseconds
AvgCounter.IncrementBy(timePiece.ElapsedMilliseconds)
AvgCounterBase.Increment()

What i'm seeing occur is:

'Elapsed counter works as expected  
'AvgCounter RawValue is 7, AvgCounterBase RawValue is also 7 before incrementing
 AvgCounter.IncrementBy(value) 'AvgCounter.RV is 7+value, AvgCounterBase is 7+value   
 AvgCounterBase.Increment()    'AvgCounter.RV is 7+value+1, AvgCounterBase is 7+value+1  

i think i may be using the counters wrong, but why does changing the rawvalue of the average seem to also change the rawvalue of the base? i dont think that's supposed to happen.

A: 

That behavior is how it should work. Increment and IncrementBy are essentially thread-safe versions of what you could do yourself by modifying RawValue directly. When the counter is only accessed by a single thread these statements:

counterVariable.RawValue++;
counterVariable.RawValue += 2;

are equivalent to these statements:

counterVariable.Increment();
counterVariable.IncrementBy(2);

If accessed by multiple threads, modifying RawValue directly is not thread-safe and can possibly lose some of the updates.

Ted Elliott
i think i may have been unclear in my question... When i call:avgcounter.incrementBy(value)avgcounterBase.increment()my base counter gets incremented by value (after the call to avgcounter) and then gets incremented once more. Does your answer still apply with that clarification?
Jugglingnutcase