ojek
ojek

Reputation: 10088

Cannot add anything to a ThreadPool

I am trying to use ThreadPool, but it is giving me errors:

class test
{
    public void testMethod1(bool param)
    {
        var something = !param;
    }

    public void testMethod2()
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(testMethod1), true); //expected a 'void testMethod1(object) signature'
        ThreadPool.QueueUserWorkItem(new WaitCallback(testMethod1(true))); //method name is expected
    }
}

How to properly use ThreadPool?

Upvotes: 1

Views: 404

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564851

The WaitCallback delegate expects a System.Object as it's argument. You would need to use that to pass in the value.

private void TestMethodWrapper(object param)
{
   TestMethod1((bool)param);
}

public void TestMethod1(bool param)
{
    var something = !param;
}

public void testMethod2()
{
    ThreadPool.QueueUserWorkItem(new WaitCallback(TestMethodWrapper), true);
}

This was the common pattern early on, but the current C# language allows more flexibility. For example, using a lambda is far simpler:

public void testMethod2()
{
    ThreadPool.QueueUserWorkItem(o => testMethod1(true));
}

When calling using this last method, the compiler effectively creates the wrapper method for you.

Upvotes: 5

spender
spender

Reputation: 120518

ThreadPool.QueueUserWorkItem(_ => testMethod1(true));

Upvotes: 2

Related Questions