How to use Interlocked Method in overlapping multi-thread cumulative Stopwatch variable

83 Views Asked by At

I have a stopwatch embedded in my progress reporting under the hoods of async/await, task. run(), and parallel. for. The stopwatch captures the duration between the process and the cumulative duration as well.

I checked my code with MessageBox.Show(Duration + " / " + CumDuration); and its giving me the correct CumDuration including the posting in my ListView table below.

But if I removed the message, the result is coming like this:

+------------------+-----------------------+
| Message          | Duration              |
+------------------+-----------------------+
| Connection open  | 0.362 sec / 0.646 sec | //should be / 0.362 sec
+------------------+-----------------------+
| Session begun    | 0.284 sec / 0.646 sec |
+------------------+-----------------------+
| Connection close | 9.108 sec / 9.855 sec | //should be / 9.754 sec
+------------------+-----------------------+
| Session end      | 0.101 sec / 9.855 sec |
+------------------+-----------------------+

Given the multithreading that were used here, I suspect because of the really tight span of time between the connection and session, the CumDuration of connection was override by session at the posting level. When I used MessageBox.Show() my code was able to cope with the right CumDuration variable.

Here are the particular codes I'm looking at right now:

Duration = Math.Round(swDuration.Elapsed.TotalSeconds, 3);
CumDuration += Duration;

I am trying to use the interlocked method but I couldn't figure out how or where to put?

Or should I use another approach?

1

There are 1 best solutions below

1
On

If you make midpointCount to keep number of milliseconds then it could be as simple as

Interlocked.Add(ref midpointCountMs, swDuration.ElapsedMilliseconds);