我有一个应用程序,我已经开始使用,似乎我需要重新思考一下。该应用程序目前是一个winform应用程序。无论如何,我允许用户输入他们想要运行的线程数量。我还允许用户分配每个线程处理的记录数。我所做的是循环线程数量变量并相应地创建线程。我没有在线程上执行任何锁定(并且不确定是否需要)。我是线程新手,并且遇到多核可能出现的问题。我需要一些建议来告诉我如何让这个表现更好。.NET多线程帮助
在创建线程之前,会从我的数据库中提取一些记录进行处理。该列表对象被发送到线程并循环播放。一旦到达循环结束,线程调用数据函数来拉取一些新记录,替换列表中的旧记录。这一直持续下去,直到没有更多的记录。这里是我的代码:
private void CreateThreads()
{
_startTime = DateTime.Now;
var totalThreads = 0;
var totalRecords = 0;
progressThreadsCreated.Maximum = _threadCount;
progressThreadsCreated.Step = 1;
LabelThreadsCreated.Text = "0/" + _threadCount.ToString();
this.Update();
for(var i = 1; i <= _threadCount; i++)
{
LabelThreadsCreated.Text = i + "/" + _threadCount;
progressThreadsCreated.Value = i;
var adapter = new Dystopia.DataAdapter();
var records = adapter.FindAllWithLocking(_recordsPerThread,_validationId,_validationDateTime);
if(records != null && records.Count > 0)
{
totalThreads += 1;
LabelTotalProcesses.Text = "Total Processes Created: " + totalThreads.ToString();
var paramss = new ArrayList { i, records };
var thread = new Thread(new ParameterizedThreadStart(ThreadWorker));
thread.Start(paramss);
}
this.Update();
}
}
private void ThreadWorker(object paramList)
{
try
{
var parms = (ArrayList) paramList;
var stopThread = false;
var threadCount = (int) parms[0];
var records = (List<Candidates>) parms[1];
var runOnce = false;
var adapter = new Dystopia.DataAdapter();
var lastCount = records.Count;
var runningCount = 0;
while (_stopThreads == false)
{
if (!runOnce)
{
CreateProgressArea(threadCount, records.Count);
}
else
{
ResetProgressBarMethod(threadCount, records.Count);
}
runOnce = true;
var counter = 0;
if (records.Count > 0)
{
foreach (var record in records)
{
counter += 1;
runningCount += 1;
_totalRecords += 1;
var rec = record;
var proc = new ProcRecords();
proc.Validate(ref rec);
adapter.Update(rec);
UpdateProgressBarMethod(threadCount, counter, emails.Count, runningCount);
if (_stopThreads)
{
break;
}
}
UpdateProgressBarMethod(threadCount, -1, lastCount, runningCount);
if (!_noRecordsInPool)
{
records = adapter.FindAllWithLocking(_recordsPerThread, _validationId, _validationDateTime);
if (records == null || records.Count <= 0)
{
_noRecordsInPool = true;
break;
}
else
{
lastCount = records.Count;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
您遇到的问题是什么? 此外,我敢肯定你需要在你的异常catch MessageBox.Show中引发UI线程。我猜如果你的进度条工作,你已经这样做,但这是一个参考问题的想法(http://stackoverflow.com/questions/2367718/c-automating-the-invokerequired-code-pattern)。因为这个,你可能会失去你的例外吗? – 2010-08-16 01:20:06
我正在使用代理来更新UI。这工作正常。尽管感谢您的反馈。 – DDiVita 2010-08-16 01:39:34