2013-07-09 42 views
2

我一直在嘗試用不同的方式來異步處理數據。我有一塊代碼在圖像處理應用程序中完成這樣的任務,但對我來說似乎很尷尬。我要尋找切合現行標準的建議,或編碼約定遵循:尋找標準替代難看多線程

' this code is run on a background thread 
Dim lockThreadCounter As New Object() 
Dim runningThreadCounter As Integer = 0 
Dim decrementCounterCallback As New AsyncCallback(
    Sub() 
     SyncLock lockThreadCounter 
      runningThreadCounter -= 1 
     End SyncLock 
    End Sub) 
runningThreadCounter += 1 
widthsAdder.BeginInvoke(widthsSlow, decrementCounterCallback, Nothing) 
runningThreadCounter += 1 
widthsAdder.BeginInvoke(widthsFast, decrementCounterCallback, Nothing) 
runningThreadCounter += 1 
bruteForceCalculateR2.BeginInvoke(numberOfSamples, pixelsSlow, decrementCounterCallback, Nothing) 
runningThreadCounter += 1 
bruteForceCalculateR2.BeginInvoke(numberOfSamples, pixelsFast, decrementCounterCallback, Nothing) 
' wait here for all four tasks to complete 
While runningThreadCounter > 0 
    Thread.Sleep(1) 
End While 
' resume with the rest of the code once all four tasks have completed 

我想過Parallel.Foreach但使用它,因爲任務有不同的委託腳印不能拿出一個解決方案。

回答

6

您可以使用Task類啓動您的工作,並使用Task.WaitAll等待它們完成。

這消除了需要有一個「正在運行的線程櫃檯」,爲每個任務可以只存儲作爲一個羣體在等待。

這看起來是這樣的(一旦你刪除你的回調):

Dim widths1 = Task.Factory.StartNew(Sub() widthsSlow()) 
Dim widths2 = Task.Factory.StartNew(Sub() widthsFast()) 
Dim bruteForce1 = Task.Factory.StartNew(Sub() numberOfSamples(pixelsSlow)) 
Dim bruteForce2 = Task.Factory.StartNew(Sub() numberOfSamples(pixelsFast)) 

' Wait for all to complete without the loop 
Task.WaitAll(widths1, widths2, bruteForce1, bruteForce2) 
+0

這正是我一直在尋找。謝謝 – djv