From 5e1306ea7ca8c9192f38ca58d4e140956a2f1d3b Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Tue, 15 Mar 2022 01:15:28 +0000 Subject: [PATCH] cosmetics: indent etc --- OpenSim/Framework/Util.cs | 550 +++++++++++++++++++------------------- 1 file changed, 275 insertions(+), 275 deletions(-) diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs index c6c885bab0..b41a63594a 100644 --- a/OpenSim/Framework/Util.cs +++ b/OpenSim/Framework/Util.cs @@ -82,8 +82,8 @@ namespace OpenSim.Framework FoldedMask = 0x0f, - FoldingShift = 13 , // number of bit shifts from normal perm to folded or back (same as Transfer shift below) - // when doing as a block + FoldingShift = 13, // number of bit shifts from normal perm to folded or back (same as Transfer shift below) + // when doing as a block Transfer = 1 << 13, // 0x02000 Modify = 1 << 14, // 0x04000 @@ -162,9 +162,9 @@ namespace OpenSim.Framework { LogThreadPool = 0; LogOverloads = true; - TimeStampClockPeriod = 1.0D/ (double)Stopwatch.Frequency; + TimeStampClockPeriod = 1.0D / (double)Stopwatch.Frequency; TimeStampClockPeriodMS = 1e3 * TimeStampClockPeriod; - m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS,6,MidpointRounding.AwayFromZero)); + m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS, 6, MidpointRounding.AwayFromZero)); } private static uint nextXferID = 5000; @@ -222,7 +222,7 @@ namespace OpenSim.Framework /// public static double lerp(double a, double b, double c) { - return (b*a) + (c*(1 - a)); + return (b * a) + (c * (1 - a)); } /// @@ -275,7 +275,7 @@ namespace OpenSim.Framework /// The distance between the two vectors public static double GetDistanceTo(Vector3 a, Vector3 b) { - return Vector3.Distance(a,b); + return Vector3.Distance(a, b); } /// @@ -287,7 +287,7 @@ namespace OpenSim.Framework /// public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount) { - return Vector3.DistanceSquared(a,b) < (amount * amount); + return Vector3.DistanceSquared(a, b) < (amount * amount); } /// @@ -332,16 +332,16 @@ namespace OpenSim.Framework public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up) { float s; - float tr = (float) (fwd.X + left.Y + up.Z + 1.0); + float tr = (float)(fwd.X + left.Y + up.Z + 1.0); if (tr >= 1.0) { - s = (float) (0.5 / Math.Sqrt(tr)); + s = (float)(0.5 / Math.Sqrt(tr)); return new Quaternion( (left.Z - up.Y) * s, (up.X - fwd.Z) * s, (fwd.Y - left.X) * s, - (float) 0.25 / s); + (float)0.25 / s); } else { @@ -349,9 +349,9 @@ namespace OpenSim.Framework if (max < fwd.X) { - s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0)); - float x = (float) (s * 0.5); - s = (float) (0.5 / s); + s = (float)(Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0)); + float x = (float)(s * 0.5); + s = (float)(0.5 / s); return new Quaternion( x, (fwd.Y + left.X) * s, @@ -360,9 +360,9 @@ namespace OpenSim.Framework } else if (max == left.Y) { - s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0)); - float y = (float) (s * 0.5); - s = (float) (0.5 / s); + s = (float)(Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0)); + float y = (float)(s * 0.5); + s = (float)(0.5 / s); return new Quaternion( (fwd.Y + left.X) * s, y, @@ -371,9 +371,9 @@ namespace OpenSim.Framework } else { - s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0)); - float z = (float) (s * 0.5); - s = (float) (0.5 / s); + s = (float)(Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0)); + float z = (float)(s * 0.5); + s = (float)(0.5 / s); return new Quaternion( (up.X + fwd.Z) * s, (left.Z + up.Y) * s, @@ -401,10 +401,10 @@ namespace OpenSim.Framework [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong RegionWorldLocToHandle(uint X, uint Y) { - ulong handle = X & 0xffffff00; // make sure it matchs grid coord points. - handle <<= 32; // to higher half - handle |= (Y & 0xffffff00); - return handle; + ulong handle = X & 0xffffff00; // make sure it matchs grid coord points. + handle <<= 32; // to higher half + handle |= (Y & 0xffffff00); + return handle; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -496,16 +496,16 @@ namespace OpenSim.Framework serviceIPstr = string.Empty; try { - Uri uri = new Uri(uristr); + Uri uri = new Uri(uristr); serviceURI = uri.AbsoluteUri; - if(uri.Port == 80) - serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) +":80/"; - else if(uri.Port == 443) - serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) +":443/"; + if (uri.Port == 80) + serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) + ":80/"; + else if (uri.Port == 443) + serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) + ":443/"; serviceHost = uri.Host; - IPEndPoint ep = Util.getEndPoint(serviceHost,uri.Port); - if(ep == null) + IPEndPoint ep = Util.getEndPoint(serviceHost, uri.Port); + if (ep == null) return false; serviceIPstr = ep.Address.ToString(); @@ -519,7 +519,7 @@ namespace OpenSim.Framework } - + public static bool buildHGRegionURI(string inputName, out string serverURI, out string regionName) { serverURI = string.Empty; @@ -539,17 +539,17 @@ namespace OpenSim.Framework string[] parts = inputName.Split(new char[] { ':' }); int indx; - if(parts.Length == 0) + if (parts.Length == 0) return false; if (parts.Length == 1) { indx = inputName.IndexOf('/'); if (indx < 0) - serverURI = "http://"+ inputName + "/"; + serverURI = "http://" + inputName + "/"; else { - serverURI = "http://"+ inputName.Substring(0,indx + 1); - if(indx + 2 < inputName.Length) + serverURI = "http://" + inputName.Substring(0, indx + 1); + if (indx + 2 < inputName.Length) regionName = inputName.Substring(indx + 1); } } @@ -560,7 +560,7 @@ namespace OpenSim.Framework if (parts.Length >= 2) { indx = parts[1].IndexOf('/'); - if(indx < 0) + if (indx < 0) { // If it's a number then assume it's a port. Otherwise, it's a region name. if (!int.TryParse(parts[1], out port)) @@ -572,7 +572,7 @@ namespace OpenSim.Framework else { string portstr = parts[1].Substring(0, indx); - if(indx + 2 < parts[1].Length) + if (indx + 2 < parts[1].Length) regionName = parts[1].Substring(indx + 1); if (!int.TryParse(portstr, out port)) port = 80; @@ -581,10 +581,10 @@ namespace OpenSim.Framework // always take the last one if (parts.Length >= 3) { - regionName = parts[2]; + regionName = parts[2]; } - serverURI = "http://"+ host +":"+ port.ToString() + "/"; + serverURI = "http://" + host + ":" + port.ToString() + "/"; } } else @@ -601,9 +601,9 @@ namespace OpenSim.Framework serverURI = parts[0]; int indx = serverURI.LastIndexOf('/'); - if(indx > 10) + if (indx > 10) { - if(indx + 2 < inputName.Length) + if (indx + 2 < inputName.Length) regionName = inputName.Substring(indx + 1); serverURI = inputName.Substring(0, indx + 1); } @@ -617,20 +617,20 @@ namespace OpenSim.Framework Uri uri; try { - uri = new Uri(serverURI); + uri = new Uri(serverURI); } catch { return false; } - if(!string.IsNullOrEmpty(regionName)) + if (!string.IsNullOrEmpty(regionName)) regionName = regionName.Trim(new char[] { '"', ' ' }); serverURI = uri.AbsoluteUri; - if(uri.Port == 80) - serverURI = serverURI.Trim(new char[] { '/', ' ' }) +":80/"; - else if(uri.Port == 443) - serverURI = serverURI.Trim(new char[] { '/', ' ' }) +":443/"; + if (uri.Port == 80) + serverURI = serverURI.Trim(new char[] { '/', ' ' }) + ":80/"; + else if (uri.Port == 443) + serverURI = serverURI.Trim(new char[] { '/', ' ' }) + ":443/"; return true; } @@ -638,12 +638,12 @@ namespace OpenSim.Framework public static T Clamp(T x, T min, T max) where T : IComparable { - if(x.CompareTo(max) > 0) + if (x.CompareTo(max) > 0) return max; - if(x.CompareTo(min) < 0) + if (x.CompareTo(min) < 0) return min; - return x; + return x; } // Clamp the maximum magnitude of a vector @@ -775,7 +775,7 @@ namespace OpenSim.Framework public static byte[] ResultFailureMessageEnd = osUTF8.GetASCIIBytes(""); public static byte[] ResultFailureMessage(string message) { - osUTF8 res = new osUTF8(ResultFailureMessageStart.Length + ResultFailureMessageEnd.Length + message.Length); + osUTF8 res = new osUTF8(ResultFailureMessageStart.Length + ResultFailureMessageEnd.Length + message.Length); res.Append(ResultFailureMessageStart); res.Append(message); res.Append(ResultFailureMessageEnd); @@ -813,7 +813,7 @@ namespace OpenSim.Framework var ids = new List(); int endA = indx + len; - if(endA > s.Length) + if (endA > s.Length) endA = s.Length; if (endA - indx < 36) return ids; @@ -1172,7 +1172,7 @@ namespace OpenSim.Framework private static byte[] ComputeMD5Hash(string data, Encoding encoding) { - using(MD5 md5 = MD5.Create()) + using (MD5 md5 = MD5.Create()) return md5.ComputeHash(encoding.GetBytes(data)); } @@ -1212,11 +1212,11 @@ namespace OpenSim.Framework public static string bytesToHexString(byte[] bytes, bool lowerCaps) { - if(bytes == null || bytes.Length == 0) + if (bytes == null || bytes.Length == 0) return string.Empty; - char[] chars = new char[2* bytes.Length]; - if(lowerCaps) + char[] chars = new char[2 * bytes.Length]; + if (lowerCaps) { for (int i = 0, j = 0; i < bytes.Length; ++i) { @@ -1399,7 +1399,7 @@ namespace OpenSim.Framework for (int j = 0; j < 16 && (i + j) < bytes.Length; j++) { if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E) - output.Append((char) bytes[i + j]); + output.Append((char)bytes[i + j]); else output.Append("."); } @@ -1418,7 +1418,7 @@ namespace OpenSim.Framework /// A resolved IP Address public static IPAddress GetHostFromURL(string url) { - return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]); + return GetHostFromDNS(url.Split(new char[] { '/', ':' })[3]); } /// @@ -1428,10 +1428,10 @@ namespace OpenSim.Framework /// An IP address, or null public static IPAddress GetHostFromDNS(string dnsAddress) { - if(String.IsNullOrWhiteSpace(dnsAddress)) + if (String.IsNullOrWhiteSpace(dnsAddress)) return null; - if(dnscache.TryGetValue(dnsAddress, 300000, out IPAddress ia) && ia != null) + if (dnscache.TryGetValue(dnsAddress, 300000, out IPAddress ia) && ia != null) return ia; ia = null; @@ -1454,7 +1454,7 @@ namespace OpenSim.Framework return null; } - if(IPH == null || IPH.AddressList.Length == 0) + if (IPH == null || IPH.AddressList.Length == 0) return null; ia = null; @@ -1469,14 +1469,14 @@ namespace OpenSim.Framework break; } } - if(ia != null) + if (ia != null) dnscache.AddOrUpdate(dnsAddress, ia, 300); return ia; } public static IPEndPoint getEndPoint(IPAddress ia, int port) { - if(ia == null) + if (ia == null) return null; IPEndPoint newEP = null; @@ -1493,10 +1493,10 @@ namespace OpenSim.Framework public static IPEndPoint getEndPoint(string hostname, int port) { - if(String.IsNullOrWhiteSpace(hostname)) + if (String.IsNullOrWhiteSpace(hostname)) return null; - if(dnscache.TryGetValue(hostname, 300000, out IPAddress ia) && ia != null) + if (dnscache.TryGetValue(hostname, 300000, out IPAddress ia) && ia != null) return getEndPoint(ia, port); ia = null; @@ -1522,7 +1522,7 @@ namespace OpenSim.Framework return null; } - if(IPH == null || IPH.AddressList.Length == 0) + if (IPH == null || IPH.AddressList.Length == 0) return null; ia = null; @@ -1538,10 +1538,10 @@ namespace OpenSim.Framework } } - if(ia != null) + if (ia != null) dnscache.AddOrUpdate(hostname, ia, 300); - return getEndPoint(ia,port); + return getEndPoint(ia, port); } public static Uri GetURI(string protocol, string hostname, int port, string path) @@ -1607,7 +1607,7 @@ namespace OpenSim.Framework if (id.Length == 0) return -1; - if(id[0] != 'h' && id[0] != 'H') + if (id[0] != 'h' && id[0] != 'H') { if (UUID.TryParse(id, out UUID luuid)) { @@ -1618,13 +1618,13 @@ namespace OpenSim.Framework } OSHTTPURI uri = new OSHTTPURI(id, true); - if(uri.IsResolvedHost) + if (uri.IsResolvedHost) { url = uri.URL; string tmp = uri.Path; - if(tmp.Length < 36) + if (tmp.Length < 36) return -3; - if(tmp[0] =='/') + if (tmp[0] == '/') tmp = tmp.Substring(1); if (UUID.TryParse(tmp, out UUID uuid)) { @@ -1765,10 +1765,10 @@ namespace OpenSim.Framework public static void AddDataRowToConfig(IConfigSource config, DataRow row) { - config.Configs.Add((string) row[0]); + config.Configs.Add((string)row[0]); for (int i = 0; i < row.Table.Columns.Count; i++) { - config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]); + config.Configs[(string)row[0]].Set(row.Table.Columns[i].ColumnName, row[i]); } } @@ -1847,13 +1847,13 @@ namespace OpenSim.Framework { IConfig enVars = ConfigSource.Configs["Environment"]; // if section does not exist then user isn't expecting them, so don't bother. - if( enVars != null ) + if (enVars != null) { // load the values from the environment EnvConfigSource envConfigSource = new EnvConfigSource(); // add the requested keys string[] env_keys = enVars.GetKeys(); - foreach ( string key in env_keys ) + foreach (string key in env_keys) { envConfigSource.AddEnv(key, string.Empty); } @@ -2260,7 +2260,7 @@ namespace OpenSim.Framework x = Utils.BytesToUInt(bytes, 8) & 0xffff; y = Utils.BytesToUInt(bytes, 12) & 0xffff; // validation may fail, just reducing the odds of using a real UUID as encoded parcel - return ( bytes[0] == 0 && bytes[4] == 0 && // handler x,y multiples of 256 + return (bytes[0] == 0 && bytes[4] == 0 && // handler x,y multiples of 256 bytes[9] < 64 && bytes[13] < 64 && // positions < 16km bytes[14] == 0 && bytes[15] == 0); } @@ -2293,19 +2293,19 @@ namespace OpenSim.Framework { string os = String.Empty; -// if (Environment.OSVersion.Platform != PlatformID.Unix) -// { -// os = Environment.OSVersion.ToString(); -// } -// else -// { -// os = ReadEtcIssue(); -// } -// -// if (os.Length > 45) -// { -// os = os.Substring(0, 45); -// } + // if (Environment.OSVersion.Platform != PlatformID.Unix) + // { + // os = Environment.OSVersion.ToString(); + // } + // else + // { + // os = ReadEtcIssue(); + // } + // + // if (os.Length > 45) + // { + // os = os.Substring(0, 45); + // } return os; } @@ -2316,18 +2316,18 @@ namespace OpenSim.Framework if (Environment.OSVersion.Platform == PlatformID.Unix) { - ru = "Unix/Mono"; + ru = "Unix/Mono"; } else if (Environment.OSVersion.Platform == PlatformID.MacOSX) - ru = "OSX/Mono"; + ru = "OSX/Mono"; + else + { + if (IsPlatformMono) + ru = "Win/Mono"; else - { - if (IsPlatformMono) - ru = "Win/Mono"; - else - ru = "Win/.NET"; - } + ru = "Win/.NET"; + } return ru; } @@ -2508,11 +2508,11 @@ namespace OpenSim.Framework public static string[] Glob(string path) { - string vol=String.Empty; + string vol = String.Empty; if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar) { - string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries); + string[] vcomps = path.Split(new char[] { Path.VolumeSeparatorChar }, 2, StringSplitOptions.RemoveEmptyEntries); if (vcomps.Length > 1) { @@ -2521,15 +2521,15 @@ namespace OpenSim.Framework } } - string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries); + string[] comps = path.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); // Glob path = vol; if (vol != String.Empty) - path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar}); + path += new String(new char[] { Path.VolumeSeparatorChar, Path.DirectorySeparatorChar }); else - path = new String(new char[] {Path.DirectorySeparatorChar}); + path = new String(new char[] { Path.DirectorySeparatorChar }); List paths = new List(); List found = new List(); @@ -2852,7 +2852,7 @@ namespace OpenSim.Framework public static bool TryParseHttpRange(string header, out int start, out int end) { start = end = 0; - if(string.IsNullOrWhiteSpace(header)) + if (string.IsNullOrWhiteSpace(header)) return false; if (header.StartsWith("bytes=")) @@ -2942,10 +2942,10 @@ namespace OpenSim.Framework case FireAndForgetMethod.SmartThreadPool: return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads; case FireAndForgetMethod.Thread: - { - using(Process p = System.Diagnostics.Process.GetCurrentProcess()) - return MAX_SYSTEM_THREADS - p.Threads.Count; - } + { + using (Process p = System.Diagnostics.Process.GetCurrentProcess()) + return MAX_SYSTEM_THREADS - p.Threads.Count; + } default: throw new NotImplementedException(); } @@ -3056,7 +3056,7 @@ namespace OpenSim.Framework // It's possible that the thread won't abort. To make sure the thread pool isn't // depleted, increase the pool size. -// m_ThreadPool.MaxThreads++; + // m_ThreadPool.MaxThreads++; } } } @@ -3123,7 +3123,7 @@ namespace OpenSim.Framework try { - if (loggingEnabled && threadInfo.LogThread) + if (loggingEnabled && threadInfo.LogThread) m_log.DebugFormat("Run threadfunc {0} (Queued {1}, Running {2})", threadFuncNum, numQueued1, numRunning1); Culture.SetCurrentCulture(); @@ -3169,7 +3169,7 @@ namespace OpenSim.Framework threadInfo.WorkItem = m_ThreadPool.QueueWorkItem(realCallback, obj); break; case FireAndForgetMethod.Thread: - Thread thread = new Thread(delegate(object o) { realCallback(o); realCallback = null;}); + Thread thread = new Thread(delegate (object o) { realCallback(o); realCallback = null; }); thread.Start(obj); break; default: @@ -3266,73 +3266,73 @@ namespace OpenSim.Framework { return null; -/* - not only this does not work on mono but it is not longer recomended on windows. - can cause deadlocks etc. + /* + not only this does not work on mono but it is not longer recomended on windows. + can cause deadlocks etc. - if (IsPlatformMono) - { - // This doesn't work in Mono - return null; - } + if (IsPlatformMono) + { + // This doesn't work in Mono + return null; + } - ManualResetEventSlim fallbackThreadReady = new ManualResetEventSlim(); - ManualResetEventSlim exitedSafely = new ManualResetEventSlim(); + ManualResetEventSlim fallbackThreadReady = new ManualResetEventSlim(); + ManualResetEventSlim exitedSafely = new ManualResetEventSlim(); - try - { - new Thread(delegate() - { - fallbackThreadReady.Set(); - while (!exitedSafely.Wait(200)) - { try { - targetThread.Resume(); + new Thread(delegate() + { + fallbackThreadReady.Set(); + while (!exitedSafely.Wait(200)) + { + try + { + targetThread.Resume(); + } + catch (Exception) + { + // Whatever happens, do never stop to resume the main-thread regularly until the main-thread has exited safely. + } + } + }).Start(); + + fallbackThreadReady.Wait(); + // From here, you have about 200ms to get the stack-trace + + targetThread.Suspend(); + + StackTrace trace = null; + try + { + trace = new StackTrace(targetThread, true); + } + catch (ThreadStateException) + { + //failed to get stack trace, since the fallback-thread resumed the thread + //possible reasons: + //1.) This thread was just too slow + //2.) A deadlock ocurred + //Automatic retry seems too risky here, so just return null. + } + + try + { + targetThread.Resume(); + } + catch (ThreadStateException) + { + // Thread is running again already + } + + return trace; } - catch (Exception) + finally { - // Whatever happens, do never stop to resume the main-thread regularly until the main-thread has exited safely. + // Signal the fallack-thread to stop + exitedSafely.Set(); } - } - }).Start(); - - fallbackThreadReady.Wait(); - // From here, you have about 200ms to get the stack-trace - - targetThread.Suspend(); - - StackTrace trace = null; - try - { - trace = new StackTrace(targetThread, true); - } - catch (ThreadStateException) - { - //failed to get stack trace, since the fallback-thread resumed the thread - //possible reasons: - //1.) This thread was just too slow - //2.) A deadlock ocurred - //Automatic retry seems too risky here, so just return null. - } - - try - { - targetThread.Resume(); - } - catch (ThreadStateException) - { - // Thread is running again already - } - - return trace; - } - finally - { - // Signal the fallack-thread to stop - exitedSafely.Set(); - } -*/ + */ } #pragma warning restore 0618 @@ -3368,7 +3368,7 @@ namespace OpenSim.Framework SmartThreadPool pool = m_ThreadPool; m_ThreadPool = null; - try { pool.Shutdown(); } catch {} + try { pool.Shutdown(); } catch { } } #endregion FireAndForget Threading Pattern @@ -4197,7 +4197,7 @@ namespace OpenSim.Framework } else if (c == '@') { - if(i >= name.Length - 1) + if (i >= name.Length - 1) return 0; int j = i; @@ -4336,7 +4336,7 @@ namespace OpenSim.Framework if (length > 250) xml = xml.Substring(0, 250) + "..."; - for (int i = 0 ; i < xml.Length ; i++) + for (int i = 0; i < xml.Length; i++) { if (xml[i] < 0x20) { @@ -4369,7 +4369,7 @@ namespace OpenSim.Framework graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; - graphics.DrawImage(image,new Rectangle(0,0, result.Width, result.Height), + graphics.DrawImage(image, new Rectangle(0, 0, result.Width, result.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, atrib); } @@ -4389,121 +4389,121 @@ namespace OpenSim.Framework bw.Close(); fs.Close(); } - } + } -/* don't like this code - public class DoubleQueue where T:class - { - private Queue m_lowQueue = new Queue(); - private Queue m_highQueue = new Queue(); - - private object m_syncRoot = new object(); - private Semaphore m_s = new Semaphore(0, 1); - - public DoubleQueue() + /* don't like this code + public class DoubleQueue where T:class { - } + private Queue m_lowQueue = new Queue(); + private Queue m_highQueue = new Queue(); - public virtual int Count - { - get + private object m_syncRoot = new object(); + private Semaphore m_s = new Semaphore(0, 1); + + public DoubleQueue() + { + } + + public virtual int Count + { + get + { + lock (m_syncRoot) + return m_highQueue.Count + m_lowQueue.Count; + } + } + + public virtual void Enqueue(T data) + { + Enqueue(m_lowQueue, data); + } + + public virtual void EnqueueLow(T data) + { + Enqueue(m_lowQueue, data); + } + + public virtual void EnqueueHigh(T data) + { + Enqueue(m_highQueue, data); + } + + private void Enqueue(Queue q, T data) { lock (m_syncRoot) - return m_highQueue.Count + m_lowQueue.Count; - } - } - - public virtual void Enqueue(T data) - { - Enqueue(m_lowQueue, data); - } - - public virtual void EnqueueLow(T data) - { - Enqueue(m_lowQueue, data); - } - - public virtual void EnqueueHigh(T data) - { - Enqueue(m_highQueue, data); - } - - private void Enqueue(Queue q, T data) - { - lock (m_syncRoot) - { - q.Enqueue(data); - m_s.WaitOne(0); - m_s.Release(); - } - } - - public virtual T Dequeue() - { - return Dequeue(Timeout.Infinite); - } - - public virtual T Dequeue(int tmo) - { - return Dequeue(TimeSpan.FromMilliseconds(tmo)); - } - - public virtual T Dequeue(TimeSpan wait) - { - T res = null; - - if (!Dequeue(wait, ref res)) - return null; - - return res; - } - - public bool Dequeue(int timeout, ref T res) - { - return Dequeue(TimeSpan.FromMilliseconds(timeout), ref res); - } - - public bool Dequeue(TimeSpan wait, ref T res) - { - if (!m_s.WaitOne(wait)) - return false; - - lock (m_syncRoot) - { - if (m_highQueue.Count > 0) - res = m_highQueue.Dequeue(); - else if (m_lowQueue.Count > 0) - res = m_lowQueue.Dequeue(); - - if (m_highQueue.Count == 0 && m_lowQueue.Count == 0) - return true; - - try { + q.Enqueue(data); + m_s.WaitOne(0); m_s.Release(); } - catch - { - } - - return true; } - } - public virtual void Clear() - { - - lock (m_syncRoot) + public virtual T Dequeue() { - // Make sure sem count is 0 - m_s.WaitOne(0); + return Dequeue(Timeout.Infinite); + } - m_lowQueue.Clear(); - m_highQueue.Clear(); + public virtual T Dequeue(int tmo) + { + return Dequeue(TimeSpan.FromMilliseconds(tmo)); + } + + public virtual T Dequeue(TimeSpan wait) + { + T res = null; + + if (!Dequeue(wait, ref res)) + return null; + + return res; + } + + public bool Dequeue(int timeout, ref T res) + { + return Dequeue(TimeSpan.FromMilliseconds(timeout), ref res); + } + + public bool Dequeue(TimeSpan wait, ref T res) + { + if (!m_s.WaitOne(wait)) + return false; + + lock (m_syncRoot) + { + if (m_highQueue.Count > 0) + res = m_highQueue.Dequeue(); + else if (m_lowQueue.Count > 0) + res = m_lowQueue.Dequeue(); + + if (m_highQueue.Count == 0 && m_lowQueue.Count == 0) + return true; + + try + { + m_s.Release(); + } + catch + { + } + + return true; + } + } + + public virtual void Clear() + { + + lock (m_syncRoot) + { + // Make sure sem count is 0 + m_s.WaitOne(0); + + m_lowQueue.Clear(); + m_highQueue.Clear(); + } } } - } -*/ + */ public class BetterRandom { private const int BufferSize = 1024; // must be a multiple of 4