diff --git a/src/OpenTelemetry/Metrics/MetricPoint.cs b/src/OpenTelemetry/Metrics/MetricPoint.cs index faa5da95d9b..b0c2c6d9324 100644 --- a/src/OpenTelemetry/Metrics/MetricPoint.cs +++ b/src/OpenTelemetry/Metrics/MetricPoint.cs @@ -40,6 +40,8 @@ public struct MetricPoint private MetricPointValueStorage deltaLastValue; + private SpinLock spinLock = new SpinLock(true); // Enable owner tracking + internal MetricPoint( AggregatorStore aggregatorStore, AggregationType aggType, @@ -336,23 +338,23 @@ internal void Update(double number) } } - var sw = default(SpinWait); - while (true) + bool lockTaken = false; + try { - if (Interlocked.Exchange(ref this.histogramBuckets.IsCriticalSectionOccupied, 1) == 0) + this.spinLock.Enter(ref lockTaken); + unchecked { - unchecked - { - this.runningValue.AsLong++; - this.histogramBuckets.RunningSum += number; - this.histogramBuckets.RunningBucketCounts[i]++; - } - - this.histogramBuckets.IsCriticalSectionOccupied = 0; - break; + this.runningValue.AsLong++; + this.histogramBuckets.RunningSum += number; + this.histogramBuckets.RunningBucketCounts[i]++; + } + } + finally + { + if (lockTaken) + { + this.spinLock.Exit(); } - - sw.SpinOnce(); } break; @@ -360,22 +362,22 @@ internal void Update(double number) case AggregationType.HistogramSumCount: { - var sw = default(SpinWait); - while (true) + bool lockTaken = false; + try { - if (Interlocked.Exchange(ref this.histogramBuckets.IsCriticalSectionOccupied, 1) == 0) + this.spinLock.Enter(ref lockTaken); + unchecked { - unchecked - { - this.runningValue.AsLong++; - this.histogramBuckets.RunningSum += number; - } - - this.histogramBuckets.IsCriticalSectionOccupied = 0; - break; + this.runningValue.AsLong++; + this.histogramBuckets.RunningSum += number; + } + } + finally + { + if (lockTaken) + { + this.spinLock.Exit(); } - - sw.SpinOnce(); } break; @@ -497,8 +499,10 @@ internal void TakeSnapshot(bool outputDelta) case AggregationType.Histogram: { - lock (this.histogramBuckets.LockObject) + bool lockTaken = false; + try { + this.spinLock.Enter(ref lockTaken); this.snapshotValue.AsLong = this.runningValue.AsLong; this.histogramBuckets.SnapshotSum = this.histogramBuckets.RunningSum; if (outputDelta) @@ -518,14 +522,23 @@ internal void TakeSnapshot(bool outputDelta) this.MetricPointStatus = MetricPointStatus.NoCollectPending; } + finally + { + if (lockTaken) + { + this.spinLock.Exit(); + } + } break; } case AggregationType.HistogramSumCount: { - lock (this.histogramBuckets.LockObject) + bool lockTaken = false; + try { + this.spinLock.Enter(ref lockTaken); this.snapshotValue.AsLong = this.runningValue.AsLong; this.histogramBuckets.SnapshotSum = this.histogramBuckets.RunningSum; if (outputDelta) @@ -536,6 +549,13 @@ internal void TakeSnapshot(bool outputDelta) this.MetricPointStatus = MetricPointStatus.NoCollectPending; } + finally + { + if (lockTaken) + { + this.spinLock.Exit(); + } + } break; }