Multiple threads calling same method in C#

前端 未结 3 585
孤城傲影
孤城傲影 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条回答
  • 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();
    }
    
    0 讨论(0)
  • 2020-12-18 13:05

    You are still 'capturing the loop variable'. You are creating a temp but too late, when i is already captured.

    Try this:

    for (int i = 0; i < 4; i++)
    {
       int temp = i;              // outside the lambda
       ts[i] = new Thread(() =>
       {
            //int temp = i;       // not here
            CallService(temp);
       });
       ts[i].Start();
    }
    
    0 讨论(0)
  • 2020-12-18 13:07

    You should put this line

    int temp = i;
    

    before the Thread creation

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

    This way you will create a local copy of i that will be used by the lambda expression.

    0 讨论(0)
提交回复
热议问题