Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Try to update the UI objects like this:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top