Please see my comment about ASP.NET.
Now, let's analyze the effect of possible parallel execution of your loop. Construction of each instance of
Employee
is independent, so each can be created in parallel. But we can reasonably assume that a constructor execution is very fast, would hardly be slower than adding a new element to the list (if it is slower, it would mean you are doing something fundamentally wrong with this constructor).
But now, pay attention that
objEmployeeList
is a resource shared by all your threads. It means that is should be done thread-save. That said, you could use for
objEmployeeList
either the thread-safe type
System.Collections.Concurrent.ConcurrentBag<Employee>
or a "regular" list class
System.Collections.Generic.List<Employee>
, but the
Add
operation should be performed under the
lock
statement.
Please see:
http://msdn.microsoft.com/en-us/library/dd381779.aspx[
^],
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx[
^],
http://msdn.microsoft.com/en-us/library/c5kehkcz%28v=vs.80%29.aspx[
^].
Is is good or bad?
It will practically nullify the effect of parallel execution, because thread-safe adding the elements to the same collection will serialize all threads by putting them in a queue waiting for access to
Add
. Each thread will quickly execute the constructor and quickly take its place in the same single queue of the threads each waiting for the access to
Add
.
What's the practical effect of it?
It will actually slow down the execution of this task, because you won't gain considerable parallelization even on many CPU cores; at the same time, the overhead cost of using threads and synchronization will eat up a good part of CPU time.
Instead of explicit use of thread you could better use
System.Threading.Tasks.Parallel.ForEach
,
http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.aspx[
^].
But will it really be much better in this case? No! The exact same considerations will be applicable, with the same result:
parallel execution is useless in this case.
The code using parallel execution for performance gain is neither usual not trivial. This approach is not applicable to everything; and the set of reasonable tasks is limited, the application of parallel execution should start with thorough analysis and design. In many cases, parallel execution as such does not help to gain sheer performance.
Eastern proverb says:
"Just saying 'halva-halva' won't make your mouth sweet."
—SA