title: Correct way to use multiple threads in C#
body: <p>i'm doing a little download manager with <strong>C#</strong> and <strong>WPF</strong>.</p>
  
  <p>In my logic there is a main thread (for UI), a thread for manage connection and a thread for each download, until a maximum download number i defined with a <strong>semaphore</strong>.</p>
  
  <p>Every time the user want to download something it adds a custom object <code>DownloadDetails</code> in a shared queue, the connection thread dequeue it and make another thread do the actual download.</p>
  
  <p>For a single file it works fine, but for multiple files looks like more threads try to download the same file, trying to write the same file on local drive and crashing when writing stream.</p>
  
  <p>Here some snippets of my implementation</p>
  
  <p>in <strong>main</strong> form:</p>
  
  <pre><code>private Thread connectionManager;
  </code></pre>
  
  <p>when clickin download i add the new download (they are all correct, i checked it) and start the connection thread only if its not already started:</p>
  
  <pre><code>downloadList.Enqueue(newDownload);
  if (connectionManager == null || !connectionManager.IsAlive)
  {
     connectionManager = new Thread((ThreadStart)delegate
     {
        ManageDownload();
     });
     connectionManager.SetApartmentState(ApartmentState.STA);
     connectionManager.IsBackground = true;
     connectionManager.Start();
  }
  </code></pre>
  
  <p>the <strong>download manager</strong> thread do this:</p>
  
  <pre><code>private void ThreadStartingPoint()
  {
      downloadDetails singleDownload = new downloadDetails();
      while (downloadList.TryDequeue(out singleDownload))
      {
          downloadSemaphore.WaitOne();
          Thread singleDownloadThread = new Thread((ThreadStart)delegate
          {
              myDownloadClass.Download(singleDownload);
          });
          singleDownloadThread.SetApartmentState(ApartmentState.STA);
          singleDownloadThread.IsBackground = false;
          singleDownloadThread.Start();
      }
  }
  </code></pre>
  
  <p>after completing the download (or canceling, or getting an error), the single thread do a <code>downloadSemaphore.Release();</code></p>
  
  <p>the problems is that the <strong>myDownloadClass.Download</strong> looks to get multiple time the same parameter when starting 2 or more downloads quickly</p>
  
  <p>i have to use delegate because single download threads needs to update UI on main thread</p>
  
  <p>how can i solve this? Thank you :)</p>