- 我有一個I/O密集型操作。
- 我只想要一次運行5個線程的MAX。
- 我有8000個任務要排隊和完成。
- 每個任務大約需要15-20秒才能執行。
我在線程池四周看了看,但是ThreadPool挫敗 - 線程創建超過SetMaxThreads
ThreadPool.SetMaxThreads(5, 0);
List<task> tasks = GetTasks();
int toProcess = tasks.Count;
ManualResetEvent resetEvent = new ManualResetEvent(false);
for (int i = 0; i < tasks.Count; i++)
{
ReportGenerator worker = new ReportGenerator(tasks[i].Code, id);
ThreadPool.QueueUserWorkItem(x =>
{
worker.Go();
if (Interlocked.Decrement(ref toProcess) == 0)
resetEvent.Set();
});
}
resetEvent.WaitOne();
我想不通爲什麼......我的代碼是在同一時間執行超過5個線程。我試過setmaxthreads,setminthreads,但它一直執行超過5個線程。
發生了什麼事?我錯過了什麼?我應該以另一種方式來做這件事嗎?
謝謝
您已經在調試器中驗證了** tasks.Count **的值嗎?你有沒有嘗試過把「5」放進去? – 2012-07-15 02:47:03
任務數組中有〜8000個對象 – Mike 2012-07-15 02:48:00