Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadPool.QueueUserWorkItem use case

Tags:

c#

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?

like image 590
A.Quiroga Avatar asked Mar 26 '12 06:03

A.Quiroga


People also ask

What is the use of ThreadPool QueueUserWorkItem method?

QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

How do you call a function using ThreadPool in C#?

After using threading namespace we need to call threadpool class, using threadpool object we need to call method i.e. "QueueUserWorkItem" - which Queues function for an execution and a function executes when a thread becomes available from thread pool. ThreadPool.

How do I limit threads in C#?

The maximum allowed number of processing threads in a pool is 1023. The pool allocates a maximum of 1000 threads in an I/O operation. To get maximum number of threads, you can use the GetMaxThreads method of the ThreadPool static class. The first parameter passed to this method returns the number of processing threads.

What is WaitCallback?

WaitCallback represents a callback method that you want to execute on a ThreadPool thread. Create the delegate by passing your callback method to the WaitCallback constructor. Your method must have the signature shown here. Queue the method for execution by passing the WaitCallback delegate to ThreadPool.


1 Answers

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.

like image 149
Jon Skeet Avatar answered Sep 28 '22 16:09

Jon Skeet