473,788 Members | 2,800 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Worker threads finish before main thread does??

15 New Member
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 1708
EricBlair
15 New Member
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;
ManualResetEven t MRE;
}

...

MethodInfo[] aMethods = aTestClass.GetM ethods();
int i = 0;
foreach(MethodI nfo aMethod in aMethods)
if(aMethod.Retu rnType.Name == "Void")
{
bundleddata aBD=new bundleddata();
aDoneEvents[i] = new ManualResetEven t(false);
aBD.Method=aMet hod ;
aBD.MRE = aDoneEvents[i];
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Th readProc), aBD);

i++;
}
Oct 12 '07 #2

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

Similar topics

10
3071
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 about 2 mins each (on a 2.8 Ghz Xeon and the server range from 2 to 8 processors) (give or take about 15 secs). I have 8 sets of calculations to do (in another app I have 121) all the same calc just different data. But the rest of the processing...
3
506
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 to the main thread to be threadsafe. I want to make this worker class I'm writing a self contained assembly so that other's can drop it into their projects. My question is: How can I NOT force those implementing my class to have to call...
6
4999
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 for long running reports. When the processing is complete it uses crystal reports to load a template file, populate it, and then export it to a PDF. It works fine so far....
7
2131
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 waits for the worker thread to complete by means of a while t.isAlive, sleep(0) mechanism. But when my worker thread calls my UpdateProgressBar routine, which calls Me.Invoke, the invoke call blocks forever. But I can't figure out why the main...
7
2695
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 a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
6
5995
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 entire operation. I could request abort on the worker thread, but that is a) potentially messy, and b) not guaranteed to take immediate effect anyway. I would rather have some way of allowing the main thread to tell the worker thread that it...
5
3548
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 only one worker thread running at any time (if a new worker thread start has been requested, any running worker thread results will be invalid). I'm using the below method to invoke a new worker thread, but when stress testing this I'm sometimes...
3
7159
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 put them in a List<>, I start them one by one then I do something like: List<ThreadElencoThreadTabelle = new List<Thread>(); ....
2
1292
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 demonstration of thread synchronization, but not quite what you want :-) Try saving the threads in a list then joining them later, like this (untested): threads =
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10364
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.