title: Display video in C# application
body: <p>I am creating a software in C#/XAML which display a video from a camera.</p>
  <p>For each frame of my video I have an OpenCV image, I manipulate the image (add circles ...) and then display the video to the user.</p>
  <p>In XAML I use the image object to display the video. The image object is linked to a WriteableBitmap, I copy my opencv image into the WriteableBitmap.</p>
  <p>Important : The WriteableBitmap is created in the main thread else the image object does'nt accept it.</p>
  <p>Main thread create the WriteableBitmap:</p>
  <pre><code>  _cameraWritableBitmap = new WriteableBitmap(
                          width,
                          height,
                          dpiX,
                          dpiY,
                          PixelFormats.Bgra32,
                          null);
  
  _mainWindow.VideoWidget.Source = _cameraWritableBitmap;
  </code></pre>
  <p>The second thread process the images :</p>
  <pre><code>//I am in a thread (not the main thread)
  Image&lt;Gray, byte&gt; img = GetFrame()
  _cameraWritableBitmap.Lock();
  //I edit the image and copy the image into _cameraWritableBitmap
  ...
  //Display the image
  _mainWindow.Dispatcher.BeginInvoke(new Action(() =&gt;
  {
       _cameraWritableBitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
       _cameraWritableBitmap.Unlock();
  }), System.Windows.Threading.DispatcherPriority.Send);
  </code></pre>
  <p>Everything is fast except Dispatcher.BeginInvoke() which is a bit random and can take 20ms. I understand that the main thread has to be ready to execute my code but I wish to improve this part.
  unfortunately AddDirtyRect must be called in the main thread.</p>
  <p>Is there a better way to display the images/video ? Maybe a method which allows the update directly from the thread ?</p>
  <p>Thank you,</p>