4

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.

Learner
  • 3,904
  • 6
  • 29
  • 44

1 Answers1

7

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 =>
{
   //...
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • that was the first thing I tried but I got this message: Cannot use lambda expression as an argument to a dynamically dispatched object without first casting it to a delegate or expression tree type. – Learner Aug 15 '13 at 22:02
  • @Learner - post the exact code you tried, and the exact error msg. – H H Aug 15 '13 at 22:05
  • @Learner You can't make the list itself dynamic - it has to be something that implements `IEnumerable` for it to work (or cast). – Reed Copsey Aug 15 '13 at 22:06
  • Thanks again for providing the solution for dynamic type. – Learner Aug 16 '13 at 02:13