WaitAll for multiple handles on a STA thread is not supported

前端 未结 5 1769
猫巷女王i
猫巷女王i 2020-12-03 00:36
  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
相关标签:
5条回答
  • 2020-12-03 01:06

    use something like this:

    foreach (ITask Task in Tasks)
    {
        Task.WaitHandle = CompletedEvent;
        new Thread(Task.Run).Start();
    }
    
    int TasksCount = Tasks.Count;
    for (int i = 0; i < TasksCount; i++)
        CompletedEvent.WaitOne();
    
    if (AllCompleted != null)
        AllCompleted(this, EventArgs.Empty);
    
    0 讨论(0)
  • 2020-12-03 01:13

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

    foreach (var e in doneEvents)
        e.WaitOne();
    
    0 讨论(0)
  • 2020-12-03 01:16

    I would refactor your code to use the CountdownEvent class instead.

    private void Search() 
    { 
        const int CPUs = 2; 
        var done = new CountdownEvent(1);
    
        // Configure and launch threads using ThreadPool: 
        for (int i = 0; i < CPUs; i++) 
        { 
            done.AddCount();
            var f = new Indexer(Paths[i], doneEvents[i]); 
            ThreadPool.QueueUserWorkItem(
              (state) =>
              {
                try
                {
                  f.WaitCallBack(state);
                }
                finally
                {
                  done.Signal();
                }
              }, i); 
        } 
    
        // Wait for all threads in pool  
        done.Signal();
        done.Wait();
        Debug.WriteLine("Search completed!"); 
    } 
    
    0 讨论(0)
  • 2020-12-03 01:17

    Use one ManualResetEvent and wait on it. Also maintain a TaskCount variable that is set to the number of worker threads you start, use Interlocked.Decrement in the worker thread code as the very last action of the worker and signal the event if the counter reaches zero,e.g.

    // other worker actions...
    if (Interlocked.Decrement(ref taskCount) == 0)
       doneEvent.Set();
    
    0 讨论(0)
  • 2020-12-03 01:30

    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);
    
    0 讨论(0)
提交回复
热议问题