添加了这个课程:
public class MyProgress
{
public string Id { get; set; }
public string Progress { get; set; }
}
dowork事件:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
List<IntPtr> intptrs = GetProcessesIntptrList();
for (int x = 0; x < intptrs.Count ; x++)
{
GetProcessInfo(intptrs[x]);
}
while (true)
{
List<MyProgress> prog = new List<MyProgress>();
prog = new List<MyProgress>();
procList = Process.GetProcesses().ToList();
for (int i = 0; i < procList.Count; i++)
{
Process[] processes = Process.GetProcessesByName(procList[i].ProcessName);
PerformanceCounter performanceCounter = new PerformanceCounter();
performanceCounter.CategoryName = "Process";
performanceCounter.CounterName = "Working Set - Private";//"Working Set";
performanceCounter.InstanceName = processes[0].ProcessName;
prog.Add(new MyProgress { Id = procList[i].ProcessName, Progress = ((uint)performanceCounter.NextValue() / 1024).ToString("N0") });
worker.ReportProgress(0, prog);
}
}
}
}
并上一次backgroundworker
progresschanged
事件,我希望将每个进程的值添加到单元格3下的datagridview1
行。
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
foreach (MyProgress p in (e.UserState as List<MyProgress>))
{
currentRow.Cells[3].Value = p.Progress;
dataGridView1.Rows.Add(
p.Progress);
}
}
变量currentRow尚不存在。我知道单元格3是我想要添加进程值的所有行的地方。
而且我也不知道应该有多少行。 以及如何将每个过程值报告到单元格3下的一行?
我在progresschanged事件中试过这个:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
foreach (MyProgress p in (e.UserState as List<MyProgress>))
{
int rowIdx = dataGridView1.Rows.Add();
dataGridView1.Rows[rowIdx].Cells[3].Value = p.Progress;
}
}
但我在foreach上获得例外: 例外是:
Additional information: Collection was modified; enumeration operation may not execute.
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Collection was modified; enumeration operation may not execute.
Source=mscorlib
StackTrace:
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at Automation.Form1.backgroundWorker1_ProgressChanged(Object sender, ProgressChangedEventArgs e) in d:\C-Sharp\Automation\Automation\Automation\Form1.cs:line 719
InnerException:
答案 0 :(得分:0)
据我了解你的问题,你需要这个
Integer rowIdx = dataGridView1.Rows.Add();
dataGridView1.Rows[rowIdx].Cells[3].Value = p.Progress
为什么错误? - 这是因为你有设计缺陷 - 在backgroundWorker1_DoWork
,它在后台线程上运行,你仍在修改集合,同时你转移到progress
事件。会发生什么,当你在一个线程上迭代它时,另一个线程会添加项目。您需要做的是复制,传递此副本并重复此副本。这是使用数组
. . . .
MyProgress[] arrP;
prog.CopyTo(arrP);
worker.ReportProgress(0, arrP);
. . .
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MyProgress[] progArr = (MyProgress[])e.UserState;
foreach (MyProgress p in progArr)
{
int rowIdx = dataGridView1.Rows.Add();
dataGridView1.Rows[rowIdx].Cells[3].Value = p.Progress;
}
}
我不确定这整个设计,所以我不想改变它。只是说现在有什么不对,不是一般的。