0

I have searched for a while regarding this problem. Got some solution, but none of them is solving my issue. The scenario is, I am fetching and processing a bitmap stream in background thread and after each frame is ready, I am trying to update the bitmap in MainWindow. I am pasting the key code-snippet here to explain the scenario.

UI Thread / MainWindow.xaml.cs

object lockObject = ThreadLockProvider.sharedInstance.LockObject;

lock (lockObject)
{
   WriteableBitmap imageFromBackgroundThread = this.webserver.getForegroundBitmap().Clone();
   this.newImage         = new WriteableBitmap(imageFromBackgroundThread );
   this.IconImage.Source = this.newImage;
}

Background Thread / ImageProcessor.cs

object lockObject = ThreadLockProvider.sharedInstance.LockObject;

lock (lockObject)
{
     // do the image processing tasks with this.foregroundBitmap                        
}

When I am executing the code, I am getting the error in the main thread - 'The calling thread cannot access this object because a different thread owns it.' Can't figure out why. Can anyone help me in solving the problems? I am already gone through this links-

Trouble with locking an image between threads

C# threading bitmap objects / picturebox

Writeablebitmap exception when having multiple threads

Thanks.

Community
  • 1
  • 1
Shuvro
  • 3
  • 2

3 Answers3

2

You have to call Freeze before using the bitmap in the UI thread. And you can only access the Image control by means of its Dispatcher:

newImage = new WriteableBitmap(imageFromBackgroundThread);
newImage.Freeze();
IconImage.Dispatcher.Invoke(new Action(() => IconImage.Source = newImage));
Clemens
  • 123,504
  • 12
  • 155
  • 268
0

Try replacing this line

this.IconImage.Source = this.newImage;

with the below code

Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
    new Action(delegate()
    {
        this.IconImage.Source = this.newImage;
    }));
Alex David
  • 585
  • 1
  • 11
  • 32
  • Don't forget to call `newImage.Freeze()` before calling the Dispatcher. @Shuvro: And do not make unnecessary copies of the bitmap, like first `Clone` and then create another new WriteableBitmap. – Clemens Apr 03 '14 at 07:53
  • Thanks for your answer. Your solution removed the runtime error, but does not sets the image in UI. Thanks @Clemens for your helpful suggestion. I have mistakenly created two copies. :( – Shuvro Apr 03 '14 at 08:24
0

Try to update the UI objects like this:

Application.Current.Dispatcher.Invoke(() => { // Update UI ojects here});

Stephen Zeng
  • 2,748
  • 21
  • 18