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

  • Anonymous
    May 03, 2011
    Change attribute [STAThread] to [MTAThreadAttribute()]. STA (Single Thread Apaerment) cannot support multiple handlers :)

  • Anonymous
    May 03, 2011
    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.

  • Anonymous
    July 25, 2011
    >>> 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.

  • Anonymous
    June 20, 2013
    Change attribute [STAThread] to [MTAThreadAttribute()] in Program.cs for c#

  • Anonymous
    June 20, 2013
    Change attribute [STAThread] to [MTAThread] in Program.cs for c#