A.Quiroga
A.Quiroga

Reputation: 5722

ThreadPool.QueueUserWorkItem use case

I'm trying to use that method this way:

public void Method()
{
        ThreadPool.QueueUserWorkItem(() =>
        {
            while(!paused)
            {
                ThreadPool.QueueUserWorkItem(() => {...);
            }
        });
    }
}

The problem comes cause it throws me a compilation error in the first call.

error CS1593: Delegate System.Threading.WaitCallback' does not take 0' arguments

Any idea of how to do it without arguments? , any alternative?

Upvotes: 5

Views: 2264

Answers (3)

Cheng Chen
Cheng Chen

Reputation: 43503

ThreadPool.QueueUserWorkItem requires a System.Threading.WaitCallback delegate as its parameter. This delegate has one parameter while your lambda expression has no. If you want to ignore the parameter you can use:

ThreadPool.QueueUserWorkItem(_ =>
{
    //...
});

Upvotes: 2

Botz3000
Botz3000

Reputation: 39600

The delegate you pass needs to take one argument. If you want to ignore it, you can just replace the brackets with any variable name.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

You can just provide a parameter for the lambda expression, and ignore it:

ThreadPool.QueueUserWorkItem(ignored =>
{
    while(!paused)
    {
        ThreadPool.QueueUserWorkItem(alsoIgnored => {...});
    }
});

Or use an anonymous method instead:

ThreadPool.QueueUserWorkItem(delegate
{
    while(!paused)
    {
        ThreadPool.QueueUserWorkItem(delegate {...});
    }
});

If you don't care about parameters for anonymous methods, you don't have to state them.

Upvotes: 12

Related Questions