Search code examples
c#.netconcurrencydelegatescaptured-variable

How to avoid captured variables?


I'm having a problem with

foreach(var category in categories)
{
    foreach(var word in words)
    {
        var waitCallback = new WaitCallback(state =>
        {
            DoSomething(word, category);
        });

        ThreadPool.QueueUserWorkItem(waitCallback);
    }
}

When the DoSomething gets executed, it receives the latest value for each captured variable instead of the value I desired. I can imagine a solution for this, but it imagine you guys can come up with better solutions


Solution

  • The canonical way to solve this is to copy the values into temporary variables which are declared inside the loop.

    foreach(var category in categories)
    {
        var catCopy = category;
        foreach(var word in words)
        {
            var wordCopy = word;
            var waitCallback = new WaitCallback(state =>
            {
                DoSomething(wordCopy, catCopy);
            });
    
            ThreadPool.QueueUserWorkItem(waitCallback);
        }
    }