Eric Blair

Eric Blair

  • NA
  • 3
  • 0

Main thread ends before worker threads do--help please??

Oct 11 2007 5:00 PM
Hello,

I've written a simple app as a test to run mutliple threads from a pool. I'm able to do this, but what's happening is that the main thread finishes before all the workers do.  So the Console shows:
"Main thread exits." in between the worker thread strings.

Can anyone see what I'm doing wrong please?

Thanks in Advance!

Here's my code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;

namespace ThreadPool2
{
   public static class Example
   {     
      private static int _MaxThreads=2;
      private static ManualResetEvent _DoneEvent;
     
      public static void Main()
      {
         // One event is used for each Method object
         ManualResetEvent[] aDoneEvents = new ManualResetEvent[3];

         Type aTestClass = typeof(Tests);
                
         ThreadPool.SetMaxThreads(_MaxThreads, _MaxThreads);

         MethodInfo[] aMethods = aTestClass.GetMethods();
         int i = 0;
         foreach(MethodInfo aMethod in aMethods)
            if(aMethod.ReturnType.Name == "Void")
            {              
               aDoneEvents[i] = new ManualResetEvent(false);
               _DoneEvent = aDoneEvents[i];
               ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), aMethod);

               i++;              
            }
        
         WaitHandle.WaitAll(aDoneEvents); //code gets stuck here but I can't see why!

         Console.WriteLine("Main thread exits.");
         Console.Read();
      }//Main

      // This thread procedure performs the task.
      static void ThreadProc(Object stateInfo)
      {
         object[] aObj = null;

         Tests aTests = new Tests(_DoneEvent);

         MethodInfo aMethod = stateInfo as MethodInfo;

         aMethod.Invoke(aTests, aObj);
                 
         aTests.DoneEvent.Set();
                 
      }//ThreadProc
   }
}



using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ThreadPool2
{
   public class Tests
   {
      public ManualResetEvent DoneEvent;

      public Tests(ManualResetEvent theDoneEvent)
      {
         DoneEvent = theDoneEvent;
      }


      public void Test1()
      {
         Console.WriteLine("This is Test 1 Start...");
         Thread.Sleep(2000);
         Console.WriteLine("This is Test 1 Stop...");
       
      }

      public void Test2()
      {

         Console.WriteLine("This is Test 2 Start...");
         Thread.Sleep(2000);
         Console.WriteLine("This is Test 2 Stop...");

       }

      public void Test3()
      {

         Console.WriteLine("This is Test 3 Start...");
         Thread.Sleep(2000);
         Console.WriteLine("This is Test 3 Stop...");

      }

   }
}





Answers (1)