Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce lock contention when sampling #1915

Merged
merged 2 commits into from
Sep 13, 2022
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: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
- Update Sentry Cocoa SDK to version 7.24.1 ([#1912](https://github.com/getsentry/sentry-dotnet/pull/1912))
- Add TransactionNameSource annotation ([#1910](https://github.com/getsentry/sentry-dotnet/pull/1910))

## Fixes

- Reduce lock contention when sampling ([#1915](https://github.com/getsentry/sentry-dotnet/pull/1915))

## 3.21.0

_Includes Sentry.Maui Preview 3_
Expand Down
43 changes: 10 additions & 33 deletions src/Sentry/Internal/SynchronizedRandom.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
using System;

#if !NET6_0_OR_GREATER
using System.Threading;
#endif

namespace Sentry.Internal
{
internal static class SynchronizedRandom
Expand All @@ -17,40 +21,13 @@ internal static class SynchronizedRandom
public static double NextDouble() => Random.Shared.NextDouble();
public static void NextBytes(byte[] bytes) => Random.Shared.NextBytes(bytes);
#else
// TODO: ThreadLocal instance would avoid contention
private static readonly Random Random = new();
private static readonly AsyncLocal<Random> LocalRandom = new();
private static Random Random => LocalRandom.Value ??= new Random();

public static void NextBytes(byte[] bytes)
{
lock (Random)
{
Random.NextBytes(bytes);
}
}

public static double NextDouble()
{
lock (Random)
{
return Random.NextDouble();
}
}

public static int Next(int minValue, int maxValue)
{
lock (Random)
{
return Random.Next(minValue, maxValue);
}
}

public static int Next()
{
lock (Random)
{
return Random.Next();
}
}
public static void NextBytes(byte[] bytes) => Random.NextBytes(bytes);
public static double NextDouble() => Random.NextDouble();
public static int Next(int minValue, int maxValue) => Random.Next(minValue, maxValue);
public static int Next() => Random.Next();
#endif
}
}