Search code examples
c#task-parallel-librarykinectwritablebitmap

WritePixels of WriteableBitmap in a Task


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);
    }
}

Solution

  • 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.