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.

0

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
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. :(
0

Try to update the UI objects like this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.