Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Sentry/Internal/ThreadsafeCounterDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ private class CounterItem
/// </summary>
/// <param name="key">The key of the counter to increment.</param>
/// <param name="quantity">The amount to add to the counter.</param>
public void Add(TKey key, int quantity) => _items.GetOrAdd(key, new CounterItem()).Add(quantity);
public void Add(TKey key, int quantity) => _items.GetOrAdd(key, static _ => new CounterItem()).Add(quantity);

/// <summary>
/// Atomically increments a counter based on the key provided, creating the counter if necessary.
/// </summary>
/// <param name="key">The key of the counter to increment.</param>
public void Increment(TKey key) => _items.GetOrAdd(key, new CounterItem()).Increment();
public void Increment(TKey key) => _items.GetOrAdd(key, static _ => new CounterItem()).Increment();

/// <summary>
/// Gets a single counter's value while atomically resetting it to zero.
Expand Down
19 changes: 19 additions & 0 deletions test/Sentry.Tests/Internals/ThreadsafeCounterDictionaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,23 @@ void ReadAndAddToGrandTotal()
const int expectedGrandTotal = numCounters * numThreadsPerCounter * numIterationsPerThread;
Assert.Equal(expectedGrandTotal, grandTotal);
}

#if NET5_0_OR_GREATER && !__MOBILE__
[Fact]
public void AddAndIncrement_ExistingCounter_DoNotAllocate()
{
var key = DiscardReason.CallbackError.WithCategory(DataCategory.LogItem);
var counters = new ThreadsafeCounterDictionary<DiscardReasonWithCategory>();
counters.Add(key, 1);
counters.Increment(key);

var before = GC.GetAllocatedBytesForCurrentThread();
counters.Add(key, 1);
counters.Increment(key);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;

Assert.Equal(0, allocated);
Assert.Equal(4, counters[key]);
}
#endif
}
Loading