title: Lock a single access variable for parallel threads in C#
body: <p>Hello i have this code</p>
  
  <pre><code>var queue = new BlockingCollection&lt;int&gt;();
              queue.Add(0);            
              var producers = Enumerable.Range(1, 3)
                  .Select(_ =&gt; Task.Factory.StartNew(()=&gt;
                      {
  
                      Enumerable.Range(1, queue.Count)
                              .ToList().ForEach(i =&gt;
                                  {
  
                                      lock (queue)
                                          {
                                              if (!queue.Contains(i))
                                              {
                                                  Console.WriteLine("Thread" + Task.CurrentId.ToString());
                                                  queue.Add(i);
                                              }
                                          }
                                      Thread.Sleep(100);
  
                                  });
  
                      }))
                   .ToArray();
  
              Task.WaitAll(producers);
              queue.CompleteAdding();
  
                  foreach (var item in queue.GetConsumingEnumerable())
                  {                    
                          Console.WriteLine(item.ToString());               
                  }   
  </code></pre>
  
  <p>But i need each time that a single thread ads something to the queue.Add(i) the 
   Enumerable.Range(1, queue.Count) to be inceased so that the code executes until there are no more items to be added to the queue. I hope you understand the question.
  In other words i need this action to run infinitely untill i tell it to stop.
  Any suggestions?</p>