WritePixels of WriteableBitmap in a Task

1.1k views Asked by At

A little n00b question I still do not understand reading, many StackOverflow answers.

The colorData variable is a byte array updated 25 times/s by Kinect. There is no UI Component.

I thought WriteableBitmap and WritePixels was called in the same Task's thread. But I still get System.InvalidOperationException. I if create a new WriteableBitmap for each loop there is no error.

How should fix my code to reuse my the WriteableBitmap in an efficient way ?

private async Task DoJob(TimeSpan dueTime, TimeSpan interval, CancellationToken token) {

  if (dueTime > TimeSpan.Zero)
    await Task.Delay(dueTime, token);

  WriteableBitmap bitmap = NewColorBitmap(colorW, colorH);

  // Repeat this loop until cancelled.
  while (!token.IsCancellationRequested) {

    try {
      bitmap.WritePixels(
        new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight),
        colorData, bitmap.PixelWidth * Bgra32BytesPerPixel, 0);
    } 
    catch(Exception ex){
      // System.InvalidOperationException: 
      // The calling thread cannot access this object 
      // because a different thread owns it.
    }

    // Wait to repeat again.
    if (interval > TimeSpan.Zero)
      await Task.Delay(interval, token);
    }
}
2

There are 2 answers

0
Jean-Philippe Encausse On BEST ANSWER

Because WriteableBitmap is bind to WPF rendering Thread I have to do complex code for inter process communication.

So I no longer use it and instead I use Image from Emgu CV (Open CV) that also have better performances.

0
Zeus On

Calling the WriteableBitmap.WritePixels method

Check the values of height and width. Perhaps the byte array is simply not big enough! And The stride is the number of bytes from one row of pixels in memory to the next row of pixels in memory.