Multiple threads calling same method in C#

前端 未结 3 584
孤城傲影
孤城傲影 2020-12-18 12:34

I have the following C# code snippet in which I have simulated my problem. In this program I have a Service function that call ReadRooms method. Now I am calling the service

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 12:56

    Your thread action is closing over the variable i instead of its current value. You therefore have a race between the thread reading i and the increment in the for loop. You can pass it as a parameter instead:

    ts[i] = new Thread(index =>
    {
        CallService((int)index);
    });
    ts[i].Start(i);
    

    alternatively you can move the copy of temp to inside the loop instead of the thread action:

    for (int i = 0; i < 4; i++)
    {
        int temp = i;
        ts[i] = new Thread(() =>
        {
            CallService(temp);
        });
        ts[i].Start();
    }
    

提交回复
热议问题