小编Sam*_*Sam的帖子

For循环结果使用Task.Run或Task.Start溢出

遇到了问题,希望有人可以帮助我.

我尝试在循环中启动4个任务,但我得到一个ArgumentOutOfRangeException:

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

循环得到溢出,因为i = 4

如果我没有循环启动任务,它们运行没有任何问题:

            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]));
Run Code Online (Sandbox Code Playgroud)

不知道为什么?来自西门子PLC的任务GetData通过套接字连接.PLC最多支持32个连接.我收到每个连接200字节.

 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 …
Run Code Online (Sandbox Code Playgroud)

c# task

10
推荐指数
1
解决办法
1220
查看次数

标签 统计

c# ×1

task ×1