C#async ThreadStart并恢复同步

时间:2011-10-22 14:54:47

标签: c# .net multithreading

我想异步启动6个线程,暂停它们并同步恢复...

它应该像这样工作:

  1. 线程1开始(thr1.start())
  2. 线程1一些进展(从txt文件获取mac-adresses,初始化com-objects)
  3. 线程1暂停(暂停,直到所有线程与线程1相同)
  4. 线程2开始
  5. 线程2一些进展
  6. 线程2已暂停
  7. 线程3开始
  8. 线程3一些进展
  9. 线程3已暂停
  10. ...
  11. 在所有6个线程暂停后,他们应该恢复所有..
  12. 我尝试了6个简单的布尔标志并等到它们都是true,但那有点脏...

    任何想法?

    编辑(更好的可视化):

    Thr1 | Initiliazing |waiting      |waiting      | Resuming
    Thr2 | waiting      |Initiliazing |waiting      | Resuming
    Thr3 | waiting      |waiting      |Initiliazing | Resuming
    ...           
    

    谢谢和问候, 通量

1 个答案:

答案 0 :(得分:3)

您需要某种同步 - 根据您的线程函数,每个线程可能会发出ManualResetEvent


编辑:感谢您的更新 - 这是一个基本的例子:

// initComplete is set by each worker thread to tell StartThreads to continue
//     with the next thread
//
// allComplete is set by StartThreads to tell the workers that they have all
//     initialized and that they may all resume


void StartThreads()
{
    var initComplete = new AutoResetEvent( false );
    var allComplete = new ManualResetEvent( false );

    var t1 = new Thread( () => ThreadProc( initComplete, allComplete ) );
    t1.Start();
    initComplete.WaitOne();

    var t2 = new Thread( () => ThreadProc( initComplete, allComplete ) );
    t2.Start();
    initComplete.WaitOne();

    // ...

    var t6 = new Thread( () => ThreadProc( initComplete, allComplete ) );
    t6.Start();
    initComplete.WaitOne();

    // allow all threads to continue
    allComplete.Set();
}


void ThreadProc( AutoResetEvent initComplete, WaitHandle allComplete )
{
    // do init

    initComplete.Set(); // signal init is complete on this thread

    allComplete.WaitOne(); // wait for signal that all threads are ready

    // resume all
}

请注意,StartThreads方法会在线程初始化时阻塞 - 这可能是也可能不是问题。