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:
Is there something wrong with this?
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.
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.