2014-10-27 140 views
0

我還沒有找到答案我能適應我的問題。C#等待其他線程

所以這是情況: 我需要測試12個網絡攝像機的功能,所有這些都在做同樣的工作。 所以,我開始12線程,連接到相機。

每個線程正在發送一個激活命令,然後等待10秒鐘的響應,這是預計不會來。

這10秒後,線程應進入等待狀態並通知主線程。

一旦所有12個線程處於等待狀態,就會通過串行連接發送命令,並且這些線程應繼續工作。現在他們應該得到答案。

到目前爲止,我得到了12個線程開始,但我不知道如何讓它們在這一點上同步。

任何幫助?

到目前爲止的代碼:

Dictionary<String, Thread> tl = new Dictionary<String, Thread>(); 
Thread t; 
foreach (String ip in this.ips) { 
    t = new Thread(new ParameterizedThreadStart(camWorker)); 
    tl.Add(ip, t); 
    tl[ip].Start(); 
} 

但它可以被重建爲每個線程創建單獨的類的實例,如果這是必需的。

+2

爲了適應多線程,您已經完成了哪些工作?即一段代碼? – 2014-10-27 13:20:00

+0

已更新問題 – WolleTD 2014-10-27 13:24:50

+0

您是在尋找一種方法來重新喚醒線索或僅保持它們的同步? – Pseudonym 2014-10-27 13:29:33

回答

2

您可以使用reset事件。爲每個線程創建一個重置事件,最後等待所有12個重置事件完成。

例子:

var resetEvents = new List<AutoResetEvent>(); 
for (int i = 0; i < 12; i++) 
{ 
    var re = new AutoResetEvent(false); 
    resetEvents.Add(re); 

    ThreadPool.QueueUserWorkItem(w => 
    { 
     var threadReset = w as AutoResetEvent; 
     var random = new Random(); 
     try 
     { 
      // do something. 
      Thread.Sleep(random.Next(100, 2000)); 
     } 
     catch (Exception ex) 
     { 
      // make sure you catch exceptions and release the lock. 
      // otherwise you will get into deadlocks 
     } 

     // when ready: 
     Console.WriteLine("Done thread " + Thread.CurrentThread.ManagedThreadId); 
     threadReset.Set(); 
    }, re); 
} 

// this bit will wait for all 12 threads to set 
foreach (AutoResetEvent resetEvent in resetEvents) 
{ 
    resetEvent.WaitOne(); 
} 

// At this point, all 12 of your threads have signaled that they're ready. 
0
bool[] timeout = new bool[12]; 
bool waitForSignal = true; 
oneof12() 
{ 
    while(true) 
    { 
     if(receivedatabeforetimeout()) 
     { 


     } 
     else 
      timeout[0] = true; 
     while(waitForSignal) 
      Thread.Sleep(500); 
    } 
} 

watcherThread() 
{ 
    bool allTimeout = true; 
    for(int a = 0; a<12;a++) 
     if(!timeout[0]) 
      allTimeout = false; 

    if(allTimeout) 
    { 
     for(int a = 0; a<12;a++) 
      timeout[a] = false; 
     waitForSignal = false; 
    } 
Thread.Sleep(200); 
} 

會是這樣的工作在你的情況?如果超時,12個線程中的每一個都將bool數組中的索引設置爲true。觀察者線程檢查布爾數組,如果所有12個超時,並且如果它們將waitForSignal標誌設置爲true,這導致12個線程離開while循環並再次等待數據

0

這聽起來像一個很好的案例任務。基本上,您可以等待12個任務,每個任務檢查一個攝像頭的狀態。這裏的優點是你不必管理你的獨立線程。

using System.Linq; 
using System.Threading.Tasks; 

... 

var Tasks = this.ips.Select(ip => Task.Run(() => Check(ip))).ToArray(); 

Task.WaitAll(Tasks); 

//inspect Task.Result to display status and perform further work 

請注意,您的Check方法可以返回一個結果,這是然後通過Task.Result訪問。 Task.WaitAll會阻止當前線程,直到所有任務運行完成。

目前還不清楚你會從這個代碼中調用什麼,但是如果合適的話,你也可以使用C#的async功能。

0

我建議使用任務爲此。

List<Task> tasks = new List<Task>(); 

for (int i=0; i<10; i++) 
{ 
    tasks.Add(Task.Factory.StartNew(() => DoSomething()); 
} 

Task.WaitAll(tasks); 

這將並行運行在後臺的所有任務,並會等待,直到他們都完成繼續。