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"*/
() => { int result1 = process1.Add(10, 11, 4); Console.Write(result1.ToString()); },
() => { int result1 = process1.Add(29, 1, 2); Console.Write(result1.ToString()); }

Run installations/apps remotely using Batch File

Today I had to install an app on multiple machines. So I used the below batch statement to copy and install the application to all machines without logging in to each box.

To use the below batch file you need psexec executable which can be downloaded from

So how do you install apps on multiple machines without logging into each box?

1) Create test_copy.bat file with below statements. Replace [MSIFILE] with the installation file name

echo off
set arg1= %arg1%
xcopy /r /y "[MSIFILE].msi" \\"%arg1%"\e$\
psexec \\%arg1% cmd.exe /c msiexec /i e:\[MSIFILE].msi /L*v install.log /qn
del \\"%arg1%"\e$\[MSIFILE].msi

2) Run "test_copy.bat" file from cmd line by specifying the machine name like "test_copy.bat -[machinename]"

That's it. You may have to provide additional parameters to "msiexec" statements to provide default installation directory etc. Also the windows user should have admin privilege on the installation box.

You can even run remote applications this way.