title: TryTake Performance on blockingcollection
body: <p>I have a programm which sometimes runs significantly slow.</p>
  
  <p>I tried Teleriks Justtrace to find out, what could possible cause a hang of the application.</p>
  
  <p>A non UI thread (therefore I believe it's not really the cause of the hang) does assync. get objects (Enqueues workitems) and deques it to do some work.</p>
  
  <p>Enqueue:</p>
  
  <pre><code>public void EnqueueObject(WorkUnit workunit)
          {
              try
              {
                  workUnits.Add(workunit);
              }
              catch (Exception ex)
              {
                  /handle exception
              }
          }
  </code></pre>
  
  <p>Dequeue:</p>
  
  <pre><code>public WorkUnit Dequeue()
          {
              try
              {
                  WorkUnit aWorkUnit  = null;
                  workUnits.TryTake(out aWorkUnit, 1000);
  
                  return aWorkUnit ;
              }
              catch (InvalidOperationException ex)
              {
                  // 
  
              }
                      return null;
          }
  </code></pre>
  
  <p>TryTake was used to check for an abort of current work (instead of the BlockingCollection Complete method which just throws some errors when called - i don't want to use errors for programm flow)</p>
  
  <p>Call to dequeue:</p>
  
  <pre><code> while(!isStopped)
   {
     ProcessWorkItem(Dequeue());
   }
  </code></pre>
  
  <p>Up to here it looks quite simple.</p>
  
  <p>The problem is, that Teleriks JustTrace shows, that the line "workUnits.TryTake(out aWorkUnit, 1000);" takes 30% of the total execution time of the program. </p>
  
  <p>How can this be? </p>
  
  <p>With more details it shows that inside the TryTake System.Threading.Monitor.Wait takes up all the time - i thought the Wait would send a thread to sleep, so it does not consume something during the wait. Where is the error in the thought?</p>