用lambda表达式和匿名方法ThreadPool.QueueUserWorkItem [英] ThreadPool.QueueUserWorkItem with a lambda expression and anonymous method

查看:777
本文介绍了用lambda表达式和匿名方法ThreadPool.QueueUserWorkItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传递两个参数的线程池一个新的线程,有时是复杂的,但现在看来,与lambda表达式和匿名方法,我可以这样做:

Passing two parameters to a new thread on the threadpool can sometimes be complicated, but it appears that with lambda expressions and anonymous methods, I can do this:

public class TestClass
{
    public void DoWork(string s1, string s2)
    {
        Console.WriteLine(s1);
        Console.WriteLine(s2);
    }
}

try
{
    TestClass test = new TestClass();
    string s1 = "Hello";
    string s2 = "World";
    ThreadPool.QueueUserWorkItem(
        o => test.DoWork(s1, s2)
        );
}
catch (Exception ex)
{
    //exception logic
}

现在,我当然简化这个例子,但这些点是关键的:

Now, I've certainly simplified this example, but these points are key:


  • 的所传递的字符串对象是不可改变的,因此线程

  • S1和S2变量try块,这是我排队的工作线程池后立即退出的范围内声明的,所以S1和S2的变量之后不会被修改。

是不是有什么问题呢?

另一种方法是创建一个实现一个不可变的类型有3名成员的新类:测试,S1和S2。这似乎只是在这一点毫无益处额外的工作。

The alternative is to create a new class that implements an immutable type with 3 members: test, s1, and s2. That just seems like extra work with no benefit at this point.

推荐答案

有什么错。编译器基本上自动做你所描述的是你的选择。它创建一个类来保存捕获的变量(测试,S1和S2),并传递一个委托实例,也就是变成对匿名类的方法拉姆达。换句话说,如果你就做你选择,你会最终soemthing非常相似,编译器只为你生成的。

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.

这篇关于用lambda表达式和匿名方法ThreadPool.QueueUserWorkItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆