ThreadPool.QueueUserWorkItem with a lambda expression and anonymous method

筅森魡賤 提交于 2019-11-30 04:35:44

There is nothing wrong with this. The compiler is essentially doing automatically what you described as your alternative. It creates a class to hold the captured variables (test, s1 and s2) and passes a delegate instance to the lambda which is turned into a method on the anonymous class. In other words, if you went ahead with your alternative you would end up with soemthing very similar to what the compiler just generated for you.

For this particular example, no there is nothing wrong here. The state you've passed into the other thread is wholely contained and none of the types involve have any thread affinity issues.

It's a nice way of doing it. I don't see any disadvantages of using lambdas. It's simple and clean.

casperOne

What you are looking at is refered to as a closure. As chuckj states, the compiler is generating a class at compile time which corresponds to the members that are accessed outside of the closure.

The only thing you have to worry about is if you have ref or out parameters. While strings are immutable, the references to them (or any variable) are NOT.

One potential problem with the pattern is that it's very tempting to expand it into something more-generic but less-safe like this (scratch code- don't expect it to work):

public static void QueueTwoParameterWorkItem<T1, T2>(T1 value1, T2 value2, workDelegate<T1,T2> work)
{
    try
    {
        T1 param1 = value1;
        T2 param2 = value2;
        ThreadPool.QueueUserWorkItem(
            (o) =>
            {
                work(param1, param2);
            });
    }
    catch (Exception ex)
    {
        //exception logic
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!