2014-04-28 49 views
0

我想動態創建X線程量(由用戶指定)然後基本上它們都在同一時間執行一些代碼,間隔爲1秒。創建X線程,同時執行一個任務

我遇到的問題是我試圖完成的任務依賴於循環來確定當前IP是否等於最後一個。 (它掃描主機)所以,因爲我有這個循環裏面,它會關閉,然後其他線程不會創建,並且不執行代碼。我希望他們都同時離開,等待1秒鐘(使用定時器或其他不鎖定線程的東西,因爲它正在執行的代碼有一個等待的超時時間。)任何人都可以幫我解決嗎?這是我目前的代碼:

  int threads = Convert.ToInt32(txtThreads.Text); 
      List<Thread> workerThreads = new List<Thread>(); 
      string from = txtStart.Text, to = txtEnd.Text; 
      uint current = from.ToUInt(), last = to.ToUInt(); 

      ulong total = last - current; 

      for (int i = 0; i < threads; i++) 
      { 
       Thread thread = new Thread(() => 
       { 
        for (int t = 0; t < Convert.ToInt32(total); t += i) 
        { 
         while (current <= last) 
         { 
          current = Convert.ToUInt32(current + t); 
          var ip = current.ToIPAddress(); 
          doSomething(ip); 
         } 
        } 
       }); 
       workerThreads.Add(thread); 
       thread.Start(); 
      } 
+1

你可以刪除你的'thread.Start'和之後的for循環,做'workerThreads.ForEach(T = > t.Start());' – Jonesopolis

+0

看來你想做網絡事情。這意味着有很大的延遲。所以大部分線程都在等待。你應該考慮一個類似於node.js的事件循環,並使用異步和等待的東西。見這裏[http://www.codeproject.com/Articles/481080/Continuous-asynchronous-Ping-using-TAP-and-IProgre]。 如果你仍然想使用線程,你也應該在每個線程上調用Join。 – schoetbi

+0

@schoetbi我實際上已經使用任務並行庫創建了一個異步實現。我正在創建這個,所以我可以做一些基準測試。我主要是在尋找速度和準確性,所以我想看看哪個實現會更快。 – user1632018

回答

3

不要使用lambda作爲線程的主體,否則i值不會做你認爲正在做的事情。而是將值傳遞給方法。

至於啓動所有的線程在同一時間做類似如下:

private object syncObj = new object(); 

void ThreadBody(object boxed) 
{ 
    Params params = (Params)boxed; 

    lock (syncObj) 
    { 
     Monitor.Wait(syncObj); 
    } 

    // do work here 
} 

struct Params 
{ 
    // passed values here 
} 

void InitializeThreads() 
{ 
    int threads = Convert.ToInt32(txtThreads.Text); 
    List<Thread> workerThreads = new List<Thread>(); 
    string from = txtStart.Text, to = txtEnd.Text; 
    uint current = from.ToUInt(), last = to.ToUInt(); 

    ulong total = last - current; 

    for (int i = 0; i < threads; i++) 
    { 
     Thread thread = new Thread(new ParameterizedThreadStart(this.ThreadBody, new Params { /* initialize values here */ })); 
     workerThreads.Add(thread); 
     thread.Start(); 
    } 

    lock(syncObj) 
    { 
     Monitor.PulseAll(syncObj); 
    } 
} 
+0

感謝您的幫助!我現在正在嘗試,我們會看到它是如何發展的。 – user1632018

+0

這很好,謝謝。 – user1632018

+0

我應該爲其他人添加,我實際上不能使用parameterizedthreadstart,並且必須使用:Thread thread = new Thread(()=> DoWork(paramobj));或者Thread thread = new Thread(()=> DoWork(param1,param2,param3));但這個答案仍然有效,除了輕微的變化。 – user1632018

0

你正在運行到關閉問題。還有一個問題可以解決這個問題,here

基本上,您需要在創建每個任務時捕獲i的值。發生什麼事是任務開始實際運行的時候,跨越所有任務的i的值是相同的 - 循環結束時的值。

相關問題