Thursday, June 13, 2013

Parallel Task in C#

I was researching parallel task in C# and found that parallelism can be achieved in different ways, mainly by using "Task" and "Parallel" methods. But internally "parallel" uses "task" to do the process.

Anyway given below are some ways to run parallel tasks in C#

Create a class called 'Process'

public class Process1
{
    public int Add(int i, int j,int k)
    {
        return i + j + k;
    }
}


Given below are different ways to call the "Add" method in parallel

/*Parallel processing using "Task"*/
Process1 process1 = new Process1();
Task<int> task1 = Task<int>.Factory.StartNew(() => process1.Add(10, 11, 4));
Task<int> task2 = Task<int>.Factory.StartNew(() => process1.Add(29, 1, 2));
Response.Write(task1.Result.ToString() + "  " + task2.Result.ToString());


/*Parallel processing using "Parallel.ForEach"*/
List<Tuple<int, int, int>> data = new List<Tuple<int, int, int>>();//Generic list for Tuple
data.Add(new Tuple<int, int, int>(10, 11, 4));//add data to list
data.Add(new Tuple<int, int, int>(29, 1, 2));
ParallelLoopResult result = Parallel.ForEach(data, item => {//Para
int result1 = process1.Add(item.Item1, item.Item2, item.Item3);
Response.Write("Parallel result "+result1.ToString());
});


/*Parallel processing using "Parallel.Invoke"*/
Parallel.Invoke(
() => { int result1 = process1.Add(10, 11, 4); Console.Write(result1.ToString()); },
() => { int result1 = process1.Add(29, 1, 2); Console.Write(result1.ToString()); }
);

No comments: