Search code examples
c#parallel.foreach

Parallel task takes longer than single task


I'm trying to create parallel task. The task call same method. Method is processing some values.

Here is the sample code:

private OpcClient client = new OpcClient();

    private void starttask()
    {
        client = new OpcClient("opc.tcp://172.16.100.1:55105");
        client.Connect();

        List<string> mytask = new List<string>();
        mytask.Add("process1");
        mytask.Add("process2");

        Parallel.For(0, 2, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i =>
        {
            mymethod(mytask[i]);

        });

    }

    private string mymethod(string node)
    {
           OpcNodeInfo machineNode = client.BrowseNode(node);
            string val = "";
            foreach (var childNode in machineNode.Children())
            {
                string _node = childNode.NodeId.ValueAsString;
               val = client.ReadNode("ns=6;s=" + _node).ToString();
                Console.WriteLine("Value = " + val);
            }

            return val;
    }

Problem is when I call this method without task the processing takes let's say 7 seconds, but calling in parallel this takes little bit more than double, so let's say 15 seconds. The method is processing same data for task1 and task2 but from different place (address)...

Why is that? Shouldn't be that both tasks are done in the same time or I'm missing something?


Solution

  • This seems to be IO Bound.

    Does the PLC support concurrent reading well? Sounds like it's bottlenecking.

    Try reading from two different PLCs and you might get faster results as well.

    If you just add some dummy calculation (or Thread.Sleep()) in mymethod(), you will see that it runs faster in parallel.