2011-10-22 93 views
0

我希望異步啓動6個線程,暫停他們並同步恢復...C#異步的ThreadStart和恢復同步

它應該工作像這樣的:

  1. 線程1開始(thr1.start( ))
  2. 線程1取得了一些進展(獲取MAC-不會忽略從TXT文件,初始化COM對象)
  3. 線程1暫停(暫停,直到所有的線程也做了同樣的線程1)
  4. 線程2開始
  5. 線程2取得了一些進展
  6. 線程2暫停
  7. 線程3起
  8. 線程3取得了一些進展
  9. 線程3暫停
  10. ...
  11. 畢竟6線程暫停,他們應該恢復所有..

我試着用6個簡單的布爾標誌並且等到它們都是true但這相當有點髒......

有什麼想法嗎?

EDIT(更好的可視化):

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

感謝和格爾茨, 通量

+0

什麼是你的問題域 - 可能有一些diffenrt方式來解決它 – swapneel

+0

爲什麼不只是執行你的主線程中的所有6'進度',然後產生額外的線程? –

+0

,因爲'一些進度'需要在每個線程..有一些messageqeue問題,如果我初始化我主要的 – MariusK

回答

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方法將發生阻塞而線程初始化 - 這可能會或可能不會是一個問題。

+0

你能給我一個小例子嗎?我不知道如何通過這個活動來實現它:(問候 – MariusK

+0

你能編輯你的問題,並且對你的線程做些什麼 - 然後我可以給出更具體的答案。 –

+0

哇謝謝...看起來像什麼即時通訊尋找!我會嘗試並給予反饋!感謝您的幫助! – MariusK