在 C# 中使用数组进行线程池,索引超出范围
Thread Pooling with Arrays in C#, index is out of range
我一直在尝试在图像过滤中使用线程池,该方法从图像中去除红色并 returns 过滤后的图像。当 y 变量达到最大数量时出现错误。我一直在寻找答案,但找不到与此相关的任何内容。
public Color[,] Apply(Color[,] input)
{
int width = input.GetLength(0);
int height = input.GetLength(1);
Color[,] result = new Color[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
ThreadPool.QueueUserWorkItem(state => Work(x, y));
}
}
void Work(int x, int y)
{
var p = input[x, y];
result[x, y] = Color.FromArgb(p.A, 0, p.G, p.B);
}
return result;
}
这里:
ThreadPool.QueueUserWorkItem(state => Work(x, y));
x
和 y
被 捕获 - 当任务运行时(在未来的某个时间点),它们(x
和y
) 不会有您所想的价值观 - 他们会继续前进。在同一范围内定义您自己的局部变量:
var xx = x;
var yy = y;
ThreadPool.QueueUserWorkItem(state => Work(xx, yy));
我一直在尝试在图像过滤中使用线程池,该方法从图像中去除红色并 returns 过滤后的图像。当 y 变量达到最大数量时出现错误。我一直在寻找答案,但找不到与此相关的任何内容。
public Color[,] Apply(Color[,] input)
{
int width = input.GetLength(0);
int height = input.GetLength(1);
Color[,] result = new Color[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
ThreadPool.QueueUserWorkItem(state => Work(x, y));
}
}
void Work(int x, int y)
{
var p = input[x, y];
result[x, y] = Color.FromArgb(p.A, 0, p.G, p.B);
}
return result;
}
这里:
ThreadPool.QueueUserWorkItem(state => Work(x, y));
x
和 y
被 捕获 - 当任务运行时(在未来的某个时间点),它们(x
和y
) 不会有您所想的价值观 - 他们会继续前进。在同一范围内定义您自己的局部变量:
var xx = x;
var yy = y;
ThreadPool.QueueUserWorkItem(state => Work(xx, yy));