From f0086865b4b944b18aa5bb32f59742c340696015 Mon Sep 17 00:00:00 2001 From: Mark Sturgill Date: Fri, 4 Oct 2013 02:33:15 -0700 Subject: [PATCH] thread safe random methods --- Server/Utility.cs | 60 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 14 deletions(-) diff --git a/Server/Utility.cs b/Server/Utility.cs index 1cd229e1f..74503ddad 100644 --- a/Server/Utility.cs +++ b/Server/Utility.cs @@ -35,6 +35,7 @@ namespace Server { public static class Utility { + // TODO: ThreadLocal for .NET 4.0? private static Random m_Random = new Random(); private static Encoding m_UTF8, m_UTF8WithEncoding; @@ -625,10 +626,6 @@ namespace Server } #endregion - public static double RandomDouble() - { - return m_Random.NextDouble(); - } #region In[...]Range public static bool InRange( Point3D p1, Point3D p2, int range ) { @@ -661,8 +658,8 @@ namespace Server && ( p1.Y >= (p2.Y - 18) ) && ( p1.Y <= (p2.Y + 18) ); } - #endregion + public static Direction GetDirection( IPoint2D from, IPoint2D to ) { int dx = to.X - from.X; @@ -774,24 +771,36 @@ namespace Server } } + #region Random //4d6+8 would be: Utility.Dice( 4, 6, 8 ) public static int Dice( int numDice, int numSides, int bonus ) { int total = 0; - for (int i=0;i 0 ) { - return from + m_Random.Next( count ); + int r; + lock (m_Random) + r = m_Random.Next( count ); + return from + r; } else { - return from - m_Random.Next( -count ); + int r; + lock (m_Random) + r = m_Random.Next( -count ); + return from - r; } } public static int Random( int count ) { - return m_Random.Next( count ); + int r; + lock (m_Random) + r = m_Random.Next( count ); + return r; } public static void RandomBytes( byte[] buffer ) { - m_Random.NextBytes( buffer ); + lock (m_Random) + m_Random.NextBytes(buffer); } + public static double RandomDouble() + { + double r; + lock (m_Random) + r = m_Random.NextDouble(); + return r; + } + #endregion + #region Random Hues ///