Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c# - For Loop result in Overflow with Task.Run or Task.Start

got a Problem, hope someone can help me out.

i try to start 4 Task in an Loop but im getting an ArgumentOutOfRangeException:

 for (int i = 0; i < 4; i++)
     {
          //start task with current connection
          tasks[i] = Task<byte[]>.Run(() => GetData(i, plcPool[i]));
     }

The Loop gets an Overflow because i = 4

if i start the Tasks without a Loop, they run without any Problems:

            tasks[0] = Task<byte[]>.Run(() => GetData(0, plcPool[0]));
            tasks[1] = Task<byte[]>.Run(() => GetData(1, plcPool[1]));
            tasks[2] = Task<byte[]>.Run(() => GetData(2, plcPool[2]));
            tasks[3] = Task<byte[]>.Run(() => GetData(3, plcPool[3]));

dont know why? The Tasks GetData from a Siemens PLC via Socket Connection. The PLC Supports up to 32 Connections. I receive 200 Bytes per Connection.

 private byte[] GetData(int id, PLC plc)
    {
        switch (id)
        {
            case 0:
                return plc.ReadBytes(DataType.DataBlock, 50, 0, 200);
            case 1:
                return plc.ReadBytes(DataType.DataBlock, 50, 200, 200);
            case 2:
                return plc.ReadBytes(DataType.DataBlock, 50, 500, 200);
            case 3:
                return plc.ReadBytes(DataType.DataBlock, 50, 700, 200);
            case 4:
                return plc.ReadBytes(DataType.DataBlock, 50, 900, 117);
            default:
                return null;
        }
    }

any idea?

Regards Sam

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's probably caused by a closure problem.

Try this:

 for (int i = 0; i < 4; i++)
 {
      //start task with current connection
      int index = i;
      tasks[index] = Task<byte[]>.Run(() => GetData(index, plcPool[index]));
 }

What is probably happening is that when the last thread starts running, the loop has already incremented i to 4, and that's the value that gets passed to GetData(). Capturing the value of i into a separate variable index and using that instead should solve that issue.

As an example, if you try this code:

public static void Main()
{
    Console.WriteLine("Starting.");

    for (int i = 0; i < 4; ++i)
        Task.Run(() => Console.WriteLine(i));

    Console.WriteLine("Finished. Press <ENTER> to exit.");
    Console.ReadLine();
}

it will often give you this kind of output:

Starting.
Finished. Press <ENTER> to exit.
4
4
4
4

Change that code to:

public static void Main()
{
    Console.WriteLine("Starting.");

    for (int i = 0; i < 4; ++i)
    {
        int j = i;
        Task.Run(() => Console.WriteLine(j));
    }

    Console.WriteLine("Finished. Press <ENTER> to exit.");
    Console.ReadLine();
}

and you get something like

Starting.
Finished. Press <ENTER> to exit.
0
1
3
2

Note how it is STILL NOT NECESSARILY IN ORDER! You will see all the correct values printed out, but in an indeterminate order. Multithreading is tricksy!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...