I have to multiply matrix by vector using class Task from TPL (it's labaratory work and I have to). I did it using Parallel For and it works but now I'm stuck because I have no idea how to implement it using tasks.
public static int[] matxvecParallel(int [,] mat, int[] vec)ParallelFor
{
int[] res = new int[mat.GetLength(0)];
Parallel.For(0, mat.GetLength(0), i =>
{
for (int k = 0; k < mat.GetLength(1); k++)
{
res[i] += mat[i, k] * vec[k];
}
});
return res;
}
I did something stupid to find out how tasks works and I still don't understand. How to change my code?
public static int[] matxvecTask(int[,] mat, int[] vec)
{
int[] res = new int[mat.GetLength(0)];
int countTasks = 4;
Task[] arrayOfTasks = new Task[countTasks];
for (int k = 0; k < mat.GetLength(0); k++)
{
for(int i = 0; i < countTasks; i++)
{
int index = i;
arrayOfTasks[index] = Task.Run(() =>
{
for (int j = 0; j < mat.GetLength(1); j++)
{
res[i] += mat[i, j] * vec[j];
}
});
}
}
return res;
}