爲線程完成一個隊列線路的最佳方式是什麼,以便我只能擁有最大數量的線程,並且如果我已經有很多代碼在等待空閒槽之前繼續..在繼續執行代碼之前等待空閒的線程槽號
我的意思僞codeish例子,我確信這可以以更好的方式來完成...
(請檢查下面的附加要求)
private int _MaxThreads = 10;
private int _CurrentThreads = 0;
public void main(string[] args)
{
List<object> listWithLotsOfItems = FillWithManyThings();
while(listWithLotsOfItems.Count> 0)
{
// get next item that needs to be worked on
var item = listWithLotsOfItems[0];
listWithLotsOfItems.RemoveAt(0);
// IMPORTANT!, more items can be added as we go.
listWithLotsOfItems.AddRange(AddMoreItemsToBeProcessed());
// wait for free thread slot
while (_CurrentThreads >= _MaxThreads)
Thread.Sleep(100);
Interlocked.Increment(ref _CurrentThreads); // risk of letting more than one thread through here...
Thread t = new Thread(new ParameterizedThreadStart(WorkerThread(item));
t.Start();
}
}
public void WorkerThread(object bigheavyObject)
{
// do heavy work here
Interlocked.Decrement(ref _CurrentThreads);
}
看着Sempahore
但似乎需要在t內運行他在線程創建之前並不在外線。在這個例子中,Semaphore在線程內部被創建後用於暫停它,在我的情況下,可能有超過10萬個線程需要在作業完成之前運行,所以我寧願在插槽可用之前創建線程。 (link to semaphore example)
在實際應用中,數據可以被添加到項目列表的程序進行所以Parallel.ForEach
將沒有真正的工作是(我在SSIS這樣的腳本組件包發送數據到一個非常慢的WCF)。
SSIS具有.NET 4.0
您是否嘗試過使用Semaphore和SemaphoreSlim? https://msdn.microsoft.com/en-us/library/system.threading.semaphoreslim%28v=vs.110%29.aspx – 2015-02-09 15:40:56
@ Benji_9989是的,請看我添加的評論。 – JensB 2015-02-09 15:42:56
傾向於使用類似['Parallel.ForEach']的構造(https://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach%28v=vs.110%29.aspx )使用MaxDegreeOfParallelism選項,而不是手動創建和管理線程(如果可能的話)。 – 2015-02-09 15:46:07