现在我每次只能报告一个值:
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)
{
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;
worker.ReportProgress(0, ((uint)performanceCounter.NextValue() / 1024).ToString("N0"));
}
}
}
}
在progresschanged事件中:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label4.Text = e.UserState.ToString();
}
但是我有更多标签,或者我可以根据dowork事件循环中报告的值的数量来创建标签。
但我们的想法是向每个标签报告一个值。而不是报告同一标签上的所有值。
答案 0 :(得分:1)
根据建议,创建一个自定义类来保存要报告的每个进程的进度。
public class MyProgress{
public string Id {get;set;}
public string Progress {get;set;}
}
如果您想在每次循环执行时报告所有进程的累积值(即将List传递给ReportProgress
调用):
while (true)
{
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);
}
然后更新事件处理程序以对我们的列表执行某些操作:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
foreach (p in (e.UserState as List<MyProgress>))
{
// Just output to console - could update label, etc...
Console.WriteLine("Progress for {0} is {1}", p.Id, p.Progress);
}
}