目标:
我正在制作一个简单的图像处理应用,该应用使用Tasks进行多线程处理。用户从文件夹中选择一个图像,并将其显示在PicBox中。当他输入线程数,要更改的colorType和该colorType(R,G,B)的Value(0-255)并单击编辑按钮时,图像为:
步骤
问题:
一切正常,直到第5步,我尝试将字节数组转换为图像。特别是在第二个任务执行期间起始索引大于0时发生。它适用于第一项任务。可能是它不接受Start Index> 0吗?
请查看以下代码:
代码
List<Task<Image>> processImgTask = new List<Task<Image>>(threadCount);
threadCount = Convert.ToInt32(threadCombox.SelectedItem);
interval = imgArray.Length / threadCount;
for (int i = 0; i < threadCount; i++)
{
Start = End;
End += interval;
if (i == threadCount - 1)
{
End = imgArray.Length;
}
object data = new object[3] { Start, End, imgArray };
processImgTask.Add(new Task<Image>(ImgProcess, data));
}
//Task.WaitAll(processImgTask);
foreach (Task<Image> task in processImgTask)
{
task.Start();
taskPicbox.Image = task.Result;
}
private Image ImgProcess(object data)
{
object[] indexes = (object[])data;
int Start=(int)indexes[0];
int End = (int)indexes[1];
byte[] img = (byte[])indexes[2];
List<byte> splitArray = new List<byte>();
for (int i =Start;i<End;i++)
{
splitArray.Add(img[i]);
}
byte[] b = splitArray.ToArray();
//Error occurs here when task 2 (thread 2) is being executed->
Image x = (Bitmap)((new ImageConverter()).ConvertFrom(b));
//System.ArgumentException: 'Parameter is not valid.'
return x;
}
请参阅how to convert a byte array with raw pixeldata to an bitmap上的答案。
我也强烈建议使用Parallel.For代替任务。任务被设计为异步运行代码,即允许计算机在等待数据时执行操作。 Parallel.For / Foreach设计为可同时运行代码,即使用多个内核以获得更好的性能。 Async and parallel is not the same。
我还建议您从要执行的操作的简单单线程实现开始。处理器是fast,除非您执行非常苛刻的操作,否则开销会很大。尽管并行化可以使您的代码运行速度提高四倍(或者不管您拥有多少CPU内核),但其他优化通常可以使性能提高数百倍甚至更多。