views:

156

answers:

3

Hi it's me again my Question is : I am trying to work with multi threading TECHNIC so I used threadPool but what I want is the following I want to identify the size of the ThreadPool when the program is launching when I have Data to manage , I will take a thread from The ThreadPool to work with this Item, as I have read you can define items in threadPool as you want but each thread will Run Automaticly I want to to have control over the thread to determine when the thread should run If no Data The thread should wait(or stop) when I have a new Data(it's like a request) one of the threads will run ..... thanks

+2  A: 

When using the ThreadPool you will typically queue a request to the pool with some (optional) input data, which will cause the pool to pick an available thread and run the process. When that is done, the thread is returned to the pool, and will be available for another request. You usually do not need to bother about managing the threads, but can simply queue a work item whenever needed:

DataToWorkWith dataItem = GetDataToWorkWith();
if (dataItem != null)
{
    ThreadPool.QueueUserWorkItem(MyProcessingMethod, dataItem);
}


// somewhere else in the class
private void MyProcessingMethod(object dataItem)
{
    // work with the dataItem; this will run on a threadpool thread, if
    // invoked through the thread pool
}

So, all you would need to do is set up some process figuring out if there is data to work with, queue the requests in the ThreadPool and let it do its job.

Fredrik Mörk
A: 

Here's a short summary on the C# ThreadPool Usage. Here's the MSDN How To: Use a ThreadPool. And here's the ThreadPool reference.

In particular, you can get the available threads using GetAvailableThreads. You can also control the min and max number of threads in the thread pool by using SetMinThreads and SetMaxThreads.

In general though, I would advise against messing with the numbers of threads, unless you know exactly what you are doing. The thread pool is shared by you and the CLR components, so by changing the number of threads you can affect the CLR behavior. For more details, read the Remarks section in the ThreadPool class documentation.

Franci Penov
A: 

You don't typically manually manage threads from the ThreadPool. The recommended usage is to queue a delegate as Fredrik exemplified, and let the ThreadPool manage the thread. With this convention, if there is no data, you shouldn't queue any work. When data becomes available, you can queue the work. If you're looking for a way to run a background process, when your application starts, you can create a Timer and add it to the application's state, or you can define a static class that manages a Timer and touch that class on application start.

gWiz