How to use Parallel.ForEach method with dynamic objects

I used the Parallel.ForEach function before processing multiple clients at the same time as follows:

Clients objClient = new Clients(); List<Clients> objClientList = Clients.GetClientList(); Parallel.ForEach<Clients>(objClientList, list => { SendFilesToClient(list); }); 

But now, instead of creating a Client class, I decided to dynamically create client objects as follows:

 var xDoc = XDocument.Load(new StreamReader(xmlPath + @"\client.xml")); dynamic root = new ExpandoObject(); XmlToDynamic.Parse(root, xDoc.Elements().First()); dynamic clients = new List<dynamic>(); for (int i = 0; i < root.clients.client.Count; i++) { clients.Add(new ExpandoObject()); clients[i].Id = root.clients.client[i].id; clients[i].Name = root.clients.client[i].name; List<string> list = new List<string>(); for (int j = 0; j < root.clients.client[i].emails.email.Count; j++) { list.Add(root.clients.client[i].emails.email[j].ToString()); } clients[i].Email = string.Join(",", list); } 

Now that I am not using the Client class and dynamically generating an object, how can I use the Parallel.ForEach function to simultaneously process several clients in a dynamic object, as it was before, before using the class object?

I hope I get it.

Also, I would appreciate it if you could tell me that something is wrong with my approach or show me the best way to do this.

+4
source share
1 answer

Now that I am not using the Client class and dynamically generating an object, how can I use the Parallel.ForEach function to simultaneously process several clients in a dynamic object, as it was before, before using the class object?

First save your list as List<T> and do not declare it as dynamic :

 List<dynamic> clients = new List<dynamic>(); 

Then you can process them the same way:

 Parallel.ForEach(clients, client => { // Use client as needed here... }); 

If you must leave clients declared as dynamic clients , you can use:

 Parallel.ForEach((IEnumerable<dynamic>)clients, client => { //... 
+6
source

Source: https://habr.com/ru/post/1497334/


All Articles