Tuesday, May 25, 2010

A simple usage of class ThreadPool (Of namespace System.Threading)

Objectives:

1. Setting the number of simultaneous threads running in the ThreadPool queue.
2. creating a state object to move to the new thread and casting it
3. Queuing a new work item.
4. Notifying the main thread of events using delegates.

ThreadPool is a static class so no constructor is needed.

On the Main Method we will set the number of Threads we want to run simultaneously using the ThreadPool class

ThreadPool.SetMaxThreads(4,4);

After setting the max threads we will create an object that will hold info to pass to the new thread

public class StateClass
    {
        public string param1 { get; set; }
        public string param2 { get; set; }
        public int param3 { get; set; }
        public string[] parametersArray { get; set; }
    }

After filling the StateClass with data we will queue the work item for processing with the state object

ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessThread), StateClass);

Create a ProcessThread method to be called from the new thread.
And cast the object passed to it to StateClass to be used inside the new thread
private void ProcessFile(object StateClassObject)
        {
            StateClass stateClassObject= (StateClass)StateClassObject;
        }

in order to interact easly with the main thread we will use a delegate (there are other options aswell like ManualResetEvent for example)

On the main class we will create a delegate (which will update a progress bar for example)

public delegate void BarDelegate();

In the ProcerssThread method add:

this.Invoke(new BarDelegate(UpdateBar));

In the main class add a method UpdateBar and do something inside

private void UpdateBar()
        {
            progressBar1.Value++;
        }

Thats about it,
Enjoy!

No comments:

Post a Comment