multi-threading and lambda variable scope

前端 未结 1 1439
無奈伤痛
無奈伤痛 2020-12-21 06:25

I am using a class that manages a pool of threads to run actions. Originally it was coded to take an Action (with no parameter) and I was calling it like this:



        
相关标签:
1条回答
  • 2020-12-21 06:39

    So the problem is that you're closing over variables that you don't mean to. The easy fix in most all cases is to create a new local variable, copy the variable you were once closing over, and then close over that instead.

    So instead of:

    for(int i = 0; i < number; i++)
    {
        threadPool.EnqueueTask(() => SomeMethod(someList[i]));
    }
    

    You can just do:

    for(int i = 0; i < number; i++)
    {
        int copy = i;
        threadPool.EnqueueTask(() => SomeMethod(someList[copy]));
    }
    

    Now each lambda is closing over it's own variable, rather than having all of them close over the same one variable.

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