Here i am creating a list of strings and using parallel foreach making a call to the method which is in server class.
and in our output you can observer the order of the elements. they are not in any particular order...
Because parallel foreach internally create a separate thread for each and every call. which will behave independently.. means each and every request will be handled asynchronously where Normal foreach is Synchronous behavior..
Note:
It is really tough to debug the calls that make in the Parallel.Foreach..
List
for (int i = 0; i < 5; i++)
{
list.Add("list item" + i.ToString());
}
Server server = new Server();
Parallel.ForEach(list, (i) => { server.GetDetails(i); });
Console.Read();
public class Server
{
public void GetDetails(dynamic item)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Request :: " + i + " " + item.ToString());
}
}
}
OutPut
Request :: 0 list item4
Request :: 1 list item4
Request :: 2 list item4
Request :: 0 list item1
Request :: 1 list item1
Request :: 0 list item2
Request :: 1 list item2
Request :: 2 list item2
Request :: 0 list item3
Request :: 1 list item3
Request :: 2 list item3
Request :: 0 list item0
Request :: 1 list item0
Request :: 2 list item0
Request :: 2 list item1
Thanks for this article. It's just what I was searching for. I am always interested in this subject.
ReplyDeletePIC Scheme Singapore