I have used Parallel.ForEach feature beafore to process multiple clients simultaneously like this:
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 have decided to create clients object dynamically like this:
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 don't use a Client class and generate the object dynamically, how do I use Parallel.ForEach feature to process multiple clients in the Dynamic Object concurrently as I used to do before using the class object?
Hope I made myself clear.
Also, I would appreciate if you could tell me if something is wrong with my approach or show me a better way of doing this.
Now that I don't use a Client class and generate the object dynamically, how do I use Parallel.ForEach feature to process multiple clients in the Dynamic Object concurrently as I used to do before using the class object?
First, keep your list as a List<T>
, and don't 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 =>
{
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With