title: How to process video frames in different thread (C#)
body: <h1>Background</h1>
  
  <p>I am working on an application that requires some image-processing on video stream and display the original video and processed video side-by-side.</p>
  
  <h1>Situtation</h1>
  
  <p>Below is the event handler when a new frame is received from camera.
  <code>pictureBox1</code>is where the original video is shown.
  <code>GetInputImage()</code> function will steal a from <code>pictureBox1</code>,so that some image processing can be performed on that frame.</p>
  
  <pre><code>private void camera_NewFrame(object sender, ref Bitmap image)
  {
      if (!isReadingPictureBox)
      {
         if (pictureBox1.Image != null)
             pictureBox1.Image.Dispose();
         pictureBox1.Image = (Bitmap)image.Clone();
      }
  }
  
  private void GetInputImage()
  {
      if (inputImage != null)
          inputImage.Dispose();
  
      isReadingPictureBox = true;
      if (pictureBox1.Image != null)
          inputImage = new Bitmap(pictureBox1.Image);
      isReadingPictureBox = false;
  }
  </code></pre>
  
  <p>The image processing is heavy and takes time to process a single image. Thus the frame rate of output video is expected to be very less that the original.</p>
  
  <p>Application must show the original video without getting affected by the image processing. So I want to perform the image processing in a different thread.</p>
  
  <pre><code>private void ProcessThread(some args)
  {
      GetInputImage();
      if (inputImage != null) {
          // Do Image Processing on &amp;quot;inputImage&amp;quot;
          // Show result in pictureBox2
      }
  }
  </code></pre>
  
  <h1>Questions</h1>
  
  <p><b>[1]</b> Is the method of grabbing a frame (above), OK ? Or the one below is better ?</p>
  
  <pre><code>private void camera_NewFrame(object sender, ref Bitmap image)
  {
      pictureBox1.Image = image; // picturBox1's image will not be read for processing
  
      if(!isReadingInputImage) {
          if (inputImage != null)
              inputImage.Dispose();
          inputImage = (Bitmap)image.Clone(); // GetInputImage() is not required now.
      }
  }
  </code></pre>
  
  <p><b>[2]</b> How to make the <code>ProcessMyThread()</code>, run for every 
  frame available at the moment when previous frame is finished processing ? Is this(below) approach OK ?</p>
  
  <pre><code>private void ProcessMyThread(some args)
  {
      do {
          GetInputImage();
          if (inputImage != null) {
              // Do Image Processing on inputImage;
              // Show result in pictureBox2
          }
      }while(someCondition);
  }
  </code></pre>
  
  <p>Or should I trigger a processing event for each frame within <code>camera_NewFrame()</code> func ?</p>