Objective:
I'm making a simple Image processing app that uses Tasks to multithread. A user selects an image from a folder and its displayed in the PicBox. When he inputs the number of threads, colorType to change and Value(0-255) of that colorType(R,G,B), and click edit button, the image is:
Procedure
- Converted to byte array
- The byte array is returned and a pivot is computed according to thread no.
- Task list is created and each task is assigned a start and end index of the larger byte array
- In the method, the small portion of larger byte (from start to end index) is saved into smaller byte array
- The method then converts the small byte array to Image and returns the image
Problem:
Everything goes fine until in the 5th step I try to convert the byte array to image. It specifically happens when the start index is greater than 0 which is during 2nd task's execution. It works ine for 1st task. Could it be that it can't accept Start Index >0?
Please look into the following code:
Code
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);
//EDIT followed by comments and answer
Parallel.ForEach(processImgTask, task =>
{
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;
}