龙4ik
会员
- 已加入
- 2020年10月24日
- 留言内容
- 16
- 编程经验
- Beginner
我遇到了这个问题,试图为函数执行设置超时。
我有以下代码:
方法 GetBestPuzzleImage() 创建函数的大调用堆栈,其中参数 清单 继续在函数中传递,直到达到终点 GetPixels(),我尝试获取每个格式 清单的 元件。还有那个地方 System.InvalidOperationException:'调用线程无法访问此对象,因为另一个线程拥有它。 被抛出:
这是来自UI线程的函数调用:
我尝试使用 冻结() 使对象跨线程的方法如下:
但是什么都没有改变。因此,我想知道为什么会发生此问题以及如何解决?
我有以下代码:
Function call:
public BitmapImage[,] GetResult(List<BitmapImage> 清单)
{
var task = Task.Run(() => GetBestPuzzleImage(list));
if (task.Wait(TimeSpan.FromSeconds(10)))
return task.Result as BitmapImage[,];
else
throw new Exception("Timed out");
}
方法 GetBestPuzzleImage() 创建函数的大调用堆栈,其中参数 清单 继续在函数中传递,直到达到终点 GetPixels(),我尝试获取每个格式 清单的 元件。还有那个地方 System.InvalidOperationException:'调用线程无法访问此对象,因为另一个线程拥有它。 被抛出:
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;
}
这是来自UI线程的函数调用:
C#:
var arr = alghoritm.GetResult(bmp);
我尝试使用 冻结() 使对象跨线程的方法如下:
C#:
private PixelColor[,] GetPixels(BitmapSource source)
{
source.Freeze();
var temp = source.Clone();
//and then code works with "temp" value
}
但是什么都没有改变。因此,我想知道为什么会发生此问题以及如何解决?