C# 如何在backgroundworker dowork事件中使用reportprogress多次报告?
现在,我每次只能报告一个值:C# 如何在backgroundworker dowork事件中使用reportprogress多次报告?,c#,.net,winforms,C#,.net,Winforms,现在,我每次只能报告一个值: private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; if ((worker.CancellationPending == true)) {
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"));
}
}
}
}
但是我有更多的标签,或者我可以根据dowork事件中循环中要报告的值的数量来创建标签
但其想法是向每个标签报告一个值。不要报告同一标签上的所有值。根据建议,创建一个自定义类来保存要报告的每个进程的进度
public class MyProgress{
public string Id {get;set;}
public string Progress {get;set;}
}
如果希望在每次执行循环时报告所有进程的累积值一次(即,将列表传递给ReportProgress
调用):
while(true)
{
List prog=新列表();
procList=Process.getprocesss().ToList();
for(int i=0;i
然后更新事件处理程序以对列表执行某些操作:
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);
}
}
private void backgroundWorker1\u ProgressChanged(对象发送方,ProgressChangedEventArgs e)
{
foreach(p在(例如UserState作为列表))
{
//只需输出到控制台-可以更新标签等。。。
WriteLine({0}的进度为{1}),p.Id,p.Progress);
}
}
您可以发送任何想要报告进度的对象。您可以定义一个类,该类指定要使用哪些值更新哪些标签,并传递其实例。
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);
}
}