diff --git a/Implab/Parallels/BlockingQueue.cs b/Implab/Parallels/BlockingQueue.cs --- a/Implab/Parallels/BlockingQueue.cs +++ b/Implab/Parallels/BlockingQueue.cs @@ -23,16 +23,21 @@ namespace Implab.Parallels { public T GetItem(int timeout) { T item; - var t1 = Environment.TickCount; - var dt = timeout; - while (!TryDequeue(out item)) { - lock (m_lock) - if (!Monitor.Wait(m_lock, dt)) - throw new TimeoutException(); - if (timeout >= 0) { - dt = timeout - Environment.TickCount + t1; - if (dt < 0) - throw new TimeoutException(); + + if (!TryDequeue(out item)) { + var t1 = Environment.TickCount; + var dt = timeout; + + lock (m_lock) { + while (!TryDequeue(out item)) { + if (!Monitor.Wait(m_lock, dt)) + throw new TimeoutException(); + if (timeout >= 0) { + dt = timeout - Environment.TickCount + t1; + if (dt < 0) + throw new TimeoutException(); + } + } } } return item; @@ -40,9 +45,11 @@ namespace Implab.Parallels { public T GetItem() { T item; - while (!TryDequeue(out item)) - lock (m_lock) - Monitor.Wait(m_lock); + if (!TryDequeue(out item)) + lock (m_lock) { + while (!TryDequeue(out item)) + Monitor.Wait(m_lock); + } return item; } @@ -51,16 +58,22 @@ namespace Implab.Parallels { var buffer = new T[max]; int actual; - var t1 = Environment.TickCount; - var dt = timeout; - while (!TryDequeueRange(buffer,0,max,out actual)) { - lock (m_lock) - if (!Monitor.Wait(m_lock, dt)) - throw new TimeoutException(); - if (timeout >= 0) { - dt = timeout - Environment.TickCount + t1; - if (dt < 0) - throw new TimeoutException(); + if (!TryDequeueRange(buffer, 0, max, out actual)) { + var t1 = Environment.TickCount; + var dt = timeout; + + lock (m_lock) { + while (!TryDequeueRange(buffer, 0, max, out actual)) { + + if (!Monitor.Wait(m_lock, dt)) + throw new TimeoutException(); + + if (timeout >= 0) { + dt = timeout - Environment.TickCount + t1; + if (dt < 0) + throw new TimeoutException(); + } + } } } @@ -74,9 +87,10 @@ namespace Implab.Parallels { var buffer = new T[max]; int actual; - while (!TryDequeueRange(buffer, 0, max, out actual)) + if (!TryDequeueRange(buffer, 0, max, out actual)) lock (m_lock) - Monitor.Wait(m_lock); + while (!TryDequeueRange(buffer, 0, max, out actual)) + Monitor.Wait(m_lock); var data = new T[actual]; Array.Copy(buffer, data, actual);