Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WaitAll for multiple handles on a STA thread is not supported

  1. Why do I get this error message? "WaitAll for multiple handles on a STA thread is not supported."
  2. Should I use [MTAThreadAttribute] attribut? Update: Dosn't work with WPF applications!

Note: It error is at line WaitHandle.WaitAll(doneEvents); I'm using a standard WPF project.

private void Search()
{
    const int CPUs = 2;
    var doneEvents = new ManualResetEvent[CPUs];

    // Configure and launch threads using ThreadPool:
    for (int i = 0; i < CPUs; i++)
    {
        doneEvents[i] = new ManualResetEvent(false);
        var f = new Indexer(Paths[i], doneEvents[i]);
        ThreadPool.QueueUserWorkItem(f.WaitCallBack, i);
    }

    // Wait for all threads in pool 
    WaitHandle.WaitAll(doneEvents);
    Debug.WriteLine("Search completed!");
}

Update: The following solution doesn’t work for WPF applications! It is not possible to change the main application attribute to MTAThreadAttribute. It will result in the following error:

Error: "WaitAll for multiple handles on a STA thread is not supported."

like image 974
Amir Rezaei Avatar asked Nov 16 '10 09:11

Amir Rezaei


2 Answers

Actually I use the following to replace WaitHandle.WaitAll(doneEvents);

foreach (var e in doneEvents)
    e.WaitOne();
like image 108
Calimero100582 Avatar answered Nov 06 '22 05:11

Calimero100582


What about using the Tasks to do your threading for you.

http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx

var task1 = Task.Factory.StartNew(() => DoSomeWork());
var task2 = Task.Factory.StartNew(() => DoSomeWork());
var task3 = Task.Factory.StartNew(() => DoSomeWork());
Task.WaitAll(task1, task2, task3);
like image 21
Oliver Avatar answered Nov 06 '22 06:11

Oliver