From da8d73b7c6e5f51c97681964773b5fe357c7608b Mon Sep 17 00:00:00 2001 From: John Gietzen Date: Tue, 31 Jul 2012 13:01:39 -0700 Subject: [PATCH] Improved the quality of randomness used for sampling. The previous version had issues with rapidly creating and disposing of StatsdPipe instances. If, say, 100 were created in the same millisecond, they would all be given the same Random seed. In this version, we use ThreadStatic storage to reduce the number of Random instances created, maintain thread safety, and allow randomness to vary much more quickly that per-millisecond. --- examples/csharp_example.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/examples/csharp_example.cs b/examples/csharp_example.cs index dfc5b0d1..eaaed09b 100644 --- a/examples/csharp_example.cs +++ b/examples/csharp_example.cs @@ -8,7 +8,17 @@ namespace Statsd public class StatsdPipe : IDisposable { private readonly UdpClient udpClient; - private readonly Random random = new Random(); + + [ThreadStatic] + private static Random random; + + private static Random Random + { + get + { + return random ?? (random = new Random()); + } + } public StatsdPipe(string host, int port) { @@ -101,7 +111,7 @@ protected bool Send(double sampleRate, params string[] stats) { foreach (var stat in stats) { - if (random.NextDouble() <= sampleRate) + if (Random.NextDouble() <= sampleRate) { var statFormatted = String.Format("{0}|@{1:f}", stat, sampleRate); if (DoSend(statFormatted))