Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8825289
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T06:50:32+00:00 2026-06-14T06:50:32+00:00

I want to know when all my async threads have completed so I know

  • 0

I want to know when all my async threads have completed so I know when to close my loading form. My code never closes the loading form. I don’t know why. I’m unsure how to correctly pass my ManualResetEvent object to the async thread too.

I’m also open to a simpler means to achieve my goal of knowing when to close the loading form.

UPDATE

After reading the advice here I’ve updated my class. Unfortunetly, it still does not work. I feel closer though. It’s just that the callback never fires.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;

namespace BrianTests
{

    public class TaskInfo
    {
        public RegisteredWaitHandle Handle;
        public string OtherInfo = "default";
        public Form loading;
    }


    public partial class AsyncControlCreateTest : Form
    {
        //List<ManualResetEvent> MREs = new List<ManualResetEvent>();
        Form loading = new Form() { Text = "Loading...", Width = 100, Height = 100 };
        CountdownWaitHandle cdwh;

        public AsyncControlCreateTest()
        {
            InitializeComponent();       
        }

        private void AsyncControlCreateTest_Load(object sender, EventArgs e)
        {            
            loading.Show(this);//I want to close when all the async threads have completed
            CreateControls();
        }  

        private void CreateControls()
        {
            int startPoint= 0;
            int threadCount = 2;
            cdwh = new CountdownWaitHandle(threadCount);

            for (int i = 0; i < threadCount; i++)
            {
                ManualResetEvent mre = new ManualResetEvent(initialState: true);                
                UserControl control = new UserControl() { Text = i.ToString() };                
                control.Load += new EventHandler(control_Load);
                Controls.Add(control);
                control.Top = startPoint;
                startPoint += control.Height;
                //MREs.Add(mre);
                //mre.Set();//just set here for testing
            }
            Task.Factory.StartNew(new Action(() => 
                {   
            TaskInfo info = new TaskInfo();
            info.loading = loading;
            try
            {
                info.Handle = ThreadPool.RegisterWaitForSingleObject(cdwh, WaitProc, info, 4000, executeOnlyOnce: false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
                })); 
        }

        public static void WaitProc(object state, bool timedOut)
        {//this callback never occurs...
            TaskInfo ti = (TaskInfo)state;

            string cause = "TIMED OUT";
            if (!timedOut)
            {
                cause = "SIGNALED";
                // If the callback method executes because the WaitHandle is 
                // signaled, stop future execution of the callback method 
                // by unregistering the WaitHandle. 
                if (ti.Handle != null)
                    ti.Handle.Unregister(null);
            }

            Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",
                ti.OtherInfo,
                Thread.CurrentThread.GetHashCode().ToString(),
                cause
            );
            ti.loading.Close();
        }


        void control_Load(object sender, EventArgs e)
        {
            RichTextBox newRichTextBox = new RichTextBox();
            UserControl control = sender as UserControl;
            control.Controls.Add(newRichTextBox);            

            Task.Factory.StartNew(new Action(() => 
                {                    
                   Thread.Sleep(2000);
                   newRichTextBox.Invoke(new Action(() => newRichTextBox.Text = "loaded"));
                   cdwh.Signal();
                })); 
        }      
    }

    public class CountdownWaitHandle : WaitHandle
    {
        private int m_Count = 0;
        private ManualResetEvent m_Event = new ManualResetEvent(false);

        public CountdownWaitHandle(int initialCount)
        {
            m_Count = initialCount;
        }

        public void AddCount()
        {
            Interlocked.Increment(ref m_Count);
        }

        public void Signal()
        {
            if (Interlocked.Decrement(ref m_Count) == 0)
            {
                m_Event.Set();
            }
        }

        public override bool WaitOne()
        {
            return m_Event.WaitOne();
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T06:50:33+00:00Added an answer on June 14, 2026 at 6:50 am

    The problem is that WaitHandle.WaitAll is throwing an exception, which you can see:

     try
     {
        WaitHandle.WaitAll(MREs.ToArray());
     }
     catch (Exception e) {
        MessageBox.Show(e.Message);
        throw;
     }
    

    The error message is that “WaitAll for multiple handles on a STA thread is not supported.”
    If you do something like

    foreach(var m in MREs)
       m.WaitOne();
    

    It will work.

    I’m not quite sure why the exception did not crash the application, as I would have hoped. See perhaps How can I get WinForms to stop silently ignoring unhandled exceptions? for this.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to know when all of the events for a mouse event have
I want to know what happened when all threads of a warp read the
The Disclaimer First of all, I know this question (or close variations) have been
I want to know all directories in the given http address. How can I
I am new to Xcode. I want to know how can I know all
There seems to be too many attributes/parameters in CSS... I want to know all
I want to know if all (or none) of the items of a Collection
I want my program always know all of the mountpoints. After a quick google
hi all i want to know that while specifying url in my iphone native
hi all i want to know that we can store information and session information

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.