473,378 Members | 1,317 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Worker threads finish before main thread does??

Hello,

I've written a simple app as a test to run multiple 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:

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Reflection;
  6.  
  7. namespace ThreadPool2
  8. {
  9.    public static class Example
  10.    {      
  11.       private static int _MaxThreads=2;
  12.       private static ManualResetEvent _DoneEvent;
  13.  
  14.       public static void Main()
  15.       {
  16.          // One event is used for each Method object
  17.          ManualResetEvent[] aDoneEvents = new ManualResetEvent[3];
  18.  
  19.          Type aTestClass = typeof(Tests);
  20.  
  21.          ThreadPool.SetMaxThreads(_MaxThreads, _MaxThreads);
  22.  
  23.          MethodInfo[] aMethods = aTestClass.GetMethods();
  24.          int i = 0;
  25.          foreach(MethodInfo aMethod in aMethods)
  26.             if(aMethod.ReturnType.Name == "Void")
  27.             {               
  28.                aDoneEvents[i] = new ManualResetEvent(false);
  29.                _DoneEvent = aDoneEvents[i];
  30.                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), aMethod);
  31.  
  32.                i++;               
  33.             }
  34.  
  35.          WaitHandle.WaitAll(aDoneEvents); //code gets stuck here but I can't see why!
  36.  
  37.          Console.WriteLine("Main thread exits.");
  38.          Console.Read();
  39.       }//Main
  40.  
  41.       // This thread procedure performs the task.
  42.       static void ThreadProc(Object stateInfo)
  43.       {
  44.          object[] aObj = null;
  45.  
  46.          Tests aTests = new Tests(_DoneEvent);
  47.  
  48.          MethodInfo aMethod = stateInfo as MethodInfo;
  49.  
  50.          aMethod.Invoke(aTests, aObj);
  51.  
  52.          aTests.DoneEvent.Set();
  53.  
  54.       }//ThreadProc
  55.    }
  56. }
  57.  
  58.  
  59.  
  60. using System;
  61. using System.Collections.Generic;
  62. using System.Text;
  63. using System.Threading;
  64.  
  65. namespace ThreadPool2
  66. {
  67.    public class Tests
  68.    {
  69.       public ManualResetEvent DoneEvent;
  70.  
  71.       public Tests(ManualResetEvent theDoneEvent)
  72.       {
  73.          DoneEvent = theDoneEvent;
  74.       }
  75.  
  76.  
  77.       public void Test1()
  78.       {
  79.          Console.WriteLine("This is Test 1 Start...");
  80.          Thread.Sleep(2000);
  81.          Console.WriteLine("This is Test 1 Stop...");
  82.  
  83.       }
  84.  
  85.       public void Test2()
  86.       {
  87.  
  88.          Console.WriteLine("This is Test 2 Start...");
  89.          Thread.Sleep(2000);
  90.          Console.WriteLine("This is Test 2 Stop...");
  91.  
  92.        }
  93.  
  94.       public void Test3()
  95.       {
  96.  
  97.          Console.WriteLine("This is Test 3 Start...");
  98.          Thread.Sleep(2000);
  99.          Console.WriteLine("This is Test 3 Stop...");
  100.  
  101.       }
  102.  
  103.    }
  104. }
  105.  
  106.  
  107.  
  108.  
  109.  
Oct 11 '07 #1
1 1672
I should have realized how sensitive threads are to timing.
Instead of having aglobal DoneEvents, I need to pass it within this loop immediately because by the time I access it beyond here, it wouls have gotten out of synch. So I bundled that data for my callback into a lightweight class that takes the doevents and the method from within the loop and passes it to my worker method.

The gist of the fix is as follows.

class bundleddata
{
MethodInfo Method;
ManualResetEvent MRE;
}

...

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

i++;
}
Oct 12 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: MikeE | last post by:
Hi all, What's the best way to queue up and wait for number of threads to complete. This problem was trivial in VC++ 6 but I'm finding it rather hard to solve in VB.NET. My calculations run...
3
by: Jacob | last post by:
I'm working on a class that needs to be called from a windows form, do it's work, and then, show progress back to the main form. I'm well aware that worker threads need to call Invoke for updates...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
7
by: Jeff Stewart | last post by:
I need a thread to run a subroutine which updates my main form's progress bar. I've properly marshaled all UI updates to the main UI thread, and after the main thread starts the worker thread, it...
7
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have...
6
by: Joe Jax | last post by:
I have an object that spawns a worker thread to process one of its methods. That method processes methods on a collection of other objects. During this processing, a user may request to cancel the...
5
by: Soren S. Jorgensen | last post by:
Hi, In my app I've got a worker thread (background) doing some calculations based upon user input. A new worker thread might be invoked before the previous worker thread has ended, and I wan't...
3
by: Ing. Davide Piras | last post by:
Hi there, in my c# .NET 2.0 application I run few threads (from 6 to 12 it depends...) and then my GUI Thread should wait all of them have finished their task... so after create those threads i...
2
by: Steve Holden | last post by:
Jonathan Shao wrote: Yes - you are calling it before you have started ALL your threads, thereby making hte main thread wait for the end of thread 1 before starting the next. An impressive...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.