I am working on an application that shows two videos side-by-side (unfortunately with custom format).
When I try to display the video frames, I get the "cannot access this object because a different thread owns it"-exception, even though I thought I calling the dispatcher would fix that.
It seems people have had similar problems when using BitmapImage
s or similar, and that they could solve the problem via freezing the image, but in my case, I receive a byte array, which does not seem to have a freeze-method.
This is the problematic code (which is called from an async method):
private void ShowVideo(string fileName)
{
ColorVideo video = new ColorVideo(fileName); // ColorVideo reads the frames from disk
WriteableBitmap image = new WriteableBitmap(video.Width, video.Height, 96, 96, PixelFormats.Bgr32, null);
// set the image as source for the image frame in the UI
this.Dispatcher.BeginInvoke((Action)delegate
{
this.ImageFrame.Source = image;
});
for (int i=0; i < video.Length, i++)
{
byte[] frameBytes = video.GetFrame(i);
// The following line throws the exception.
// wrapping the line inside a call to Dispatcher doesn't help
// I get the cross-thread exception regardless
image.WritePixels(new Int32Rect(0,0,video.Width,video.Height),frameBytes, video.Width*4,0);
}
}
Now, I suspect that I my approach may not actually be ideal, anyway. All I want is to be able to run a showVideo
method in the background and have it update the image shown 30 times a second. How can I do this better?