In my application I'm opening image data in a task. But when I'm tying to request the a property from the BitmapSource inside a while loop in the same function as I created the image I get the following error:
The calling thread cannot access this object because a different thread owns it
But when I call the property before the while loop it works without a problem. This while it is in the same function, as far as my knowledge goes this should all be the same Thread? So why do I get the error?
Code that gives me the error:
public AnalogInputs()
{
Task.Run(() =>
{
AnalogInputsSimulationTask();
});
}
private async void AnalogInputsSimulationTask()
{
BitmapSource bSource = new BitmapImage(new Uri("pack://application:,,,/Images/HBT_Light_Diode_Simulation.bmp"));
while (true)
{
var bytesPerPixel = (bSource.Format.BitsPerPixel + 7) / 8; //This line gives the error
await Task.Delay(1);
}
}
But when I Format the AnalogInputsSimulationTask Function like this it doesn't give me the error:
private async void AnalogInputsSimulationTask()
{
BitmapSource bSource = new BitmapImage(new Uri("pack://application:,,,/Images/HBT_Light_Diode_Simulation.bmp"));
var bytesPerPixel = (bSource.Format.BitsPerPixel + 7) / 8; //Now there is no error
while (true)
{
await Task.Delay(1);
}
}
As this is a very stripped down version of my problem, I need the first format to work, I want to load the image once and then do stuff with it in the while loop. But I cannot access it in the while loop.
I know this error usually comes up when you try to access GUI stuff from within a Task, but I'm now doing everything in the Task and the image isn't shown or used in the GUI anywhere.