-1

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?

RickyBelmont
  • 619
  • 4
  • 11
  • 1
    [Threading in C# - ADVANCED THREADING - Nonblocking Synchronization - Interlocked](https://www.albahari.com/threading/part4.aspx#_Interlocked) by ​Joseph Albahari. – Theodor Zoulias Aug 12 '22 at 02:18
  • 1
    Thanks, man! I've been hearing this name. I thought this was something else. I will look into this now. – RickyBelmont Aug 12 '22 at 02:21
  • It's unclear what trying to accomplish with the CumDuration variable based upon the question (i.e. single global StopWatch, local, or both - cum increment and duration). If you post a copy of the code, I can definitely get it sorted for you. –  Sep 20 '22 at 12:39

1 Answers1

1

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

Interlocked.Add(ref midpointCountMs, swDuration.ElapsedMilliseconds);
tymtam
  • 31,798
  • 8
  • 86
  • 126
  • Thank you for this man! But I'm still getting the same result. I created an `int` variable for `midpointCount` and `(int)swDuration.ElapsedMilliseconds`. Unless, I am doing it wrong. – RickyBelmont Aug 14 '22 at 04:48