title: efficiently saving image files to disk c#
body: <p>We're developing a multi-sensor aquisition tool, and we're experiencing problems with saving the images (from a webcam) to the hard drive.</p>
  
  <p>We are using three threads for that purpose:</p>
  
  <ul>
  <li>One thread that continuously gathers the captured image from the webcam. </li>
  <li>A timer thread that collects the last image and sends it into a file saving method. </li>
  <li>The timer thread calls a third thread to save, in order not to interfere with the main timer thread functionality.</li>
  </ul>
  
  <p>This works fine for low frequencies. When we raise the FPS to around 30, we start losing images. Notice that we have multiple sensors and not just a webcam. That's why we're using this architecture and not directly saving files from the webcam thread (we need to keep everything synced)</p>
  
  <p>This is the current implementation of the save method:</p>
  
  <pre><code>private void saveImageFrame(Bitmap b, ulong frameID)
      {
          string fileSavePath = _path+ "//";
          if (b != null)
          {
              Task.Factory.StartNew(() =&gt;
              {
                  lock (_lock)
                  {
                      Bitmap toSave = new Bitmap(b);
                      string fileName = fileSavePath + frameID.ToString() + ".bmp";
                      toSave.Save(fileName);
                  }
              });
          }
      }
  </code></pre>
  
  <p>We also tried without the Task thread (for saving) and without the lock. These two result in race conditions, since the saving takes more time than the timer time interval.</p>
  
  <p>I'm sure there are better ways to do this both in terms of architecture and .NET functions. Any help in enhancing the performance of this would be greatly appreciated!</p>