Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ThreadPool class

Status
Not open for further replies.

sand133

Programmer
Jun 26, 2004
103
0
0
GB
I have the following code...

static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Method));
}
}
// This thread procedure performs the task.
static void Method(Object stateInfo)
{
//do some work
}
}

My question is the main thread exits before the threadpool task gets a chance to run, How do i over come this? I have looked at MSDN and they say use Thread.Sleep(), does anyone have a more elegant solution.
 
Yup. Your worker threads need to tell their parent thread when they're done with their work assignment.

You usually do this via a ManualResetEvent object or an Interlocked.Increment call.

Don't use a boolean variable to indicate 'done-ness' -- they're not 100% thread-safe.

Chip H.


____________________________________________________________________
www.chipholland.com
 
As chiph suggested one solution to your scenario is to use the ManualResetEvent. Chiph is right about using the boolean variables not being thread safe. This is because even statements like "stop=true" where stop is bool will consist of more than one instruction when compiled.

I tried a simple example of using ManualResetEvent below

Code:
class Program
    {
        //A manual reset event as suggested by Chiph
        static ManualResetEvent finished;

        static void Main(string[] args)
        {
            Console.WriteLine("Main program started");

            //Create the "finished" event with initial state="Has not happened"
            finished = new ManualResetEvent(false); 
            
            //Fire up the thread pool 
            ThreadPool.QueueUserWorkItem(Method);

            //Create the "finished" event to "happen"
            finished.WaitOne();
            

            Console.WriteLine("Main program stopped");
    
        }

        
        static void Method(Object stateInfo)
        {
              
            Console.WriteLine("Lets do some work");

            Thread.Sleep(3000);

            Console.WriteLine("Finished work ");

            //Now set the "finished" event   
            finished.Set();
        }
    }

Hope this helps.



"It is in our collective behaviour that we are most mysterious" Lewis Thomas
 
Thanks bledazemi that was the perfect solution.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top