WaitHandle.WaitAll For Multiple Handles on a STA Thread Is Not Supported


While developing WinForm application, if you need to spawn multiple threads to work on different tasks and you need to wait all threads to complete ... then you might think to use the following approach:

>>> Create an array of AutoResetEvent; use ThreadPool.QueueUserWorkerItem to spawn each task in different thread; then call WaitHandle.WaitAll(AutoResetEvent[]) to wait all threads to complete the task

WinForm app is attributed as [STAThread] and you will get "WaitAll For Multiple Handles on a STA Thread Is Not Supported" error ... what's the solution? Here is what I used for this scenario:

>>> Create a ManualResetEvent; maintain a TaskCounter; use ThreadPool.QueueUserWorkerItem to spawn each task in different thread; Call ManualResetEvent.WaitOne(); Decrement the TaskCounter after each task is completed and Call ManualResetEvent.Set() when the TaskCounter == 0

Special notes: In your DoTask(object stateInfo), you need to handle exception properly and make sure the TaskCounter is subtracted should there is an exception 


Comments (5)
  1. Change attribute [STAThread] to [MTAThreadAttribute()].

    STA (Single Thread Apaerment) cannot support multiple handlers 🙂

  2. pursca says:

    COM objects in an STA thread are synchronized using the message queue,

    so "waiting" without pumping messages is not a good idea. Some functions like OpenFileDialog will not work in MTA.

  3. KABOOM says:

    >>> Create an array of ManualResetEvent; use ThreadPool.QueueUserWorkerItem to spawn each task in different thread; then call WaitHandle.WaitOne() for all manualResetEvents (foreach loop), to wait all threads to complete the task

    Peace.

  4. Amit Rajput says:

    Change attribute [STAThread] to [MTAThreadAttribute()] in Program.cs for c#

  5. Amit Rajput says:

    Change attribute [STAThread] to [MTAThread] in Program.cs for c#

Comments are closed.

Skip to main content