Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to wait for multiple STA threads to finish?

How to wait for multiple STA threads to finish?

Scheduled Pinned Locked Moved C#
comtutorialquestion
6 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    SandeepN
    wrote on last edited by
    #1

    I create multiple STA threads and start them. Once I have started all the threads in my main thread I need to wait till all of them are done. To wait I tried WaitHandle.WaitAll() ----- returns exception Tried waitEvent.waitOne() and thread.Join() In above case some times my main thread slips through Join\waitOne(). (i.e. main thread does not wait till all other threads are done) Please advice how to implement this? My sample code is as below Main() { ... ... ArrayList myThreadClass = new ArrayList(3); ArrayList threads = new ArrayList(3); for(int i = 0 ; i< 3;i++) { ThreadClass thClass = new ThreadClass(); myThreadClass.Add(thClass); Thread myThread = new Thread( new ThreadStart(thClass.threadMethod)); myThread.ApartmentState = ApartmentState.STA; threads.Add(myThread); ((Thread)threads[i]).Start(); } for(int k = 0;k<3;k++) { ((Thread)threads[k]).Join(); } ..... ..... } //Main Ends Some more info In my thread method I do some COM calls and make some callls Writeline to StreamWriter

    Sandeep Naik

    N 1 Reply Last reply
    0
    • S SandeepN

      I create multiple STA threads and start them. Once I have started all the threads in my main thread I need to wait till all of them are done. To wait I tried WaitHandle.WaitAll() ----- returns exception Tried waitEvent.waitOne() and thread.Join() In above case some times my main thread slips through Join\waitOne(). (i.e. main thread does not wait till all other threads are done) Please advice how to implement this? My sample code is as below Main() { ... ... ArrayList myThreadClass = new ArrayList(3); ArrayList threads = new ArrayList(3); for(int i = 0 ; i< 3;i++) { ThreadClass thClass = new ThreadClass(); myThreadClass.Add(thClass); Thread myThread = new Thread( new ThreadStart(thClass.threadMethod)); myThread.ApartmentState = ApartmentState.STA; threads.Add(myThread); ((Thread)threads[i]).Start(); } for(int k = 0;k<3;k++) { ((Thread)threads[k]).Join(); } ..... ..... } //Main Ends Some more info In my thread method I do some COM calls and make some callls Writeline to StreamWriter

      Sandeep Naik

      N Offline
      N Offline
      Nader Elshehabi
      wrote on last edited by
      #2

      Hello You can go through your threads using a loop and check the IsAlive property of each

      bool Finished = false;

      while(!Finished)
      {
      Finished = true;
      foreach(Thread T in Threads)
      {
      if(T.IsAlive)
      Finished = false;
      }
      Thread.Sleep(100)
      }

      Otherwise you can check the ThreadState property

      Regards:rose:

      S 2 Replies Last reply
      0
      • N Nader Elshehabi

        Hello You can go through your threads using a loop and check the IsAlive property of each

        bool Finished = false;

        while(!Finished)
        {
        Finished = true;
        foreach(Thread T in Threads)
        {
        if(T.IsAlive)
        Finished = false;
        }
        Thread.Sleep(100)
        }

        Otherwise you can check the ThreadState property

        Regards:rose:

        S Offline
        S Offline
        SandeepN
        wrote on last edited by
        #3

        Will I be blocking message pump here ?

        Sandeep Naik

        S 1 Reply Last reply
        0
        • S SandeepN

          Will I be blocking message pump here ?

          Sandeep Naik

          S Offline
          S Offline
          SandeepN
          wrote on last edited by
          #4

          I tried something like this and it works with some of my testing .. Do you think if this correct ? or will there be any issues with this for(int temp = 0; temp Sandeep Naik

          N 1 Reply Last reply
          0
          • S SandeepN

            I tried something like this and it works with some of my testing .. Do you think if this correct ? or will there be any issues with this for(int temp = 0; temp Sandeep Naik

            N Offline
            N Offline
            Nader Elshehabi
            wrote on last edited by
            #5

            Hello Your code segments are inconsistent and somehow don't add up!! For example what is GRDumpThread?? Anyway, if you want to use WaitHandle class, you should register your threads in ther ThreadPool queue. Take a look at this example taken from MSDN:

            using System;
            using System.Threading;

            public sealed class App
            {
            // Define an array with two AutoResetEvent WaitHandles.
            static WaitHandle[] waitHandles = new WaitHandle[]
            {
            new AutoResetEvent(false),
            new AutoResetEvent(false)
            };

            // Define a random number generator for testing.
            static Random r = new Random();
            
            static void Main() 
            {
                // Queue up two tasks on two different threads; 
                // wait until all tasks are completed.
                DateTime dt = DateTime.Now;
                Console.WriteLine("Main thread is waiting for BOTH tasks to complete.");
                ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles\[0\]);
                ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles\[1\]);
                WaitHandle.WaitAll(waitHandles);
                // The time shown below should match the longest task.
                Console.WriteLine("Both tasks are completed (time waited={0})", 
                    (DateTime.Now - dt).TotalMilliseconds);
            
                // Queue up two tasks on two different threads; 
                // wait until any tasks are completed.
                dt = DateTime.Now;
                Console.WriteLine();
                Console.WriteLine("The main thread is waiting for either task to complete.");
                ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles\[0\]);
                ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles\[1\]);
                int index = WaitHandle.WaitAny(waitHandles);
                // The time shown below should match the shortest task.
                Console.WriteLine("Task {0} finished first (time waited={1}).",
                    index + 1, (DateTime.Now - dt).TotalMilliseconds);
            }
            
            static void DoTask(Object state) 
            {
                AutoResetEvent are = (AutoResetEvent) state;
                int time = 1000 \* r.Next(2, 10);
                Console.WriteLine("Performing a task for {0} milliseconds.", time);
                Thread.Sleep(time);
                are.Set();
            }
            

            }

            // This code produces output similar to the following:
            //
            // Main thread is waiting for BOTH tasks to complete.
            // Performing a task for 7000 milliseconds.
            // Performing a task for 4000 milliseconds.
            // Both tasks are completed (time waited=7064.8052)
            //
            // The main thread is waiting for either ta

            1 Reply Last reply
            0
            • N Nader Elshehabi

              Hello You can go through your threads using a loop and check the IsAlive property of each

              bool Finished = false;

              while(!Finished)
              {
              Finished = true;
              foreach(Thread T in Threads)
              {
              if(T.IsAlive)
              Finished = false;
              }
              Thread.Sleep(100)
              }

              Otherwise you can check the ThreadState property

              Regards:rose:

              S Offline
              S Offline
              SandeepN
              wrote on last edited by
              #6

              Thanks for all your help... It was very use full

              Sandeep Naik

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups