Dragon4ik
Member
- Joined
- Oct 24, 2020
- Messages
- 16
- Programming Experience
- Beginner
I've faced with the problem, trying to set a timeout for function execution.
I have the following code:
Method GetBestPuzzleImage() creates big call stack of functions, where parameter list continues be passed in functions, until it gets the final point GetPixels(), where I try to get the format of every list's element. And there is the place, where System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.' is thrown:
And here is the function call from the UI thread:
I try to use to use Freeze() method to make an object cross-thread in such way:
But nothing changed. So I want to know why this problem happens and how to solve it?
I have the following code:
Function call:
public BitmapImage[,] GetResult(List<BitmapImage> list)
{
var task = Task.Run(() => GetBestPuzzleImage(list));
if (task.Wait(TimeSpan.FromSeconds(10)))
return task.Result as BitmapImage[,];
else
throw new Exception("Timed out");
}
Method GetBestPuzzleImage() creates big call stack of functions, where parameter list continues be passed in functions, until it gets the final point GetPixels(), where I try to get the format of every list's element. And there is the place, where System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.' is thrown:
C#:
private PixelColor[,] GetPixels(BitmapSource source)
{
if (source.Format != PixelFormats.Bgra32) //here exception is thrown
{
source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
}
int width = source.PixelWidth;
int height = source.PixelHeight;
PixelColor[,] result = new PixelColor[width, height];
source.CopyPixels(result, width * 4, 0, true);
return result;
}
And here is the function call from the UI thread:
C#:
var arr = alghoritm.GetResult(bmp);
I try to use to use Freeze() method to make an object cross-thread in such way:
C#:
private PixelColor[,] GetPixels(BitmapSource source)
{
source.Freeze();
var temp = source.Clone();
//and then code works with "temp" value
}
But nothing changed. So I want to know why this problem happens and how to solve it?