I would like to use QueueUserWorkItem from ThreadPool. When I use the following code, everything works well.
private int ThreadCountSemaphore = 0; private void (...) { var reportingDataList = new List<LBReportingData>(); ThreadCountSemaphore = reportingDataList.Count; using (var autoResetEvent = new AutoResetEvent(false)) { ThreadPool.QueueUserWorkItem((o) => this.FillReportingData(settings, reportingDataList[0], autoResetEvent)); ThreadPool.QueueUserWorkItem((o) => this.FillReportingData(settings, reportingDataList[1], autoResetEvent)); ThreadPool.QueueUserWorkItem((o) => this.FillReportingData(settings, reportingDataList[2], autoResetEvent)); } } private void FillReportingData(...) { if (Interlocked.Decrement(ref this.ThreadCountSemaphore) == 0) { waitHandle.Set(); } }
But when I use a list instead of a single method, my program crashes without exception.
private void (...) { var reportingDataList = new List<LBReportingData>(); ThreadCountSemaphore = reportingDataList.Count; using (var autoResetEvent = new AutoResetEvent(false)) { ThreadPool.QueueUserWorkItem((o) => this.FillReportingData(settings, reportingDataList[i], autoResetEvent)); } }
What am I wrong? What should I change?
Update
Sorry, I made a mistake in the code. I am using .NET 2.0 with VS2010. Here is the full code:
private int ThreadCountSemaphore = 0; private IList<LBReportingData> LoadReportsForBatch() { var reportingDataList = new List<LBReportingData>(); var settings = OnNeedEntitySettings(); if (settings.Settings.ReportDefinition != null) { var definitionList = new List<ReportDefinitionen> { ReportDefinitionen.OrgStatus, ReportDefinitionen.Mittelwerte, ReportDefinitionen.Verteilungsstatistik }; using (var autoResetEvent = new AutoResetEvent(false)) { foreach (var reportDefinition in definitionList) { foreach (DataRow row in settings.Settings.ReportDefinition.Select("AuswertungsTyp = " + (int)reportDefinition)) { reportingDataList.Add(new LBReportingData { SourceData = row, ReportType = reportDefinition }); } } ThreadCountSemaphore = reportingDataList.Count; foreach(var reportingDataItem in reportingDataList) { ThreadPool.QueueUserWorkItem((o) => this.FillReportingData(settings, reportingDataItem, autoResetEvent)); } autoResetEvent.WaitOne(); } } return reportingDataList; } private void FillReportingData(IEntitySettings<DSLBUReportDefinition> settings, LBReportingData reportingData, AutoResetEvent waitHandle){ DoSomeWork(); if (Interlocked.Decrement(ref this.ThreadCountSemaphore) == 0) { waitHandle.Set(); } }
thank
multithreading c # threadpool
Dani Sep 15 '10 at 17:23 2010-09-15 17:23
source share