离开这个...... https://www.codeproject.com/Articles/841751/MultiThreading-Using-a-Background-Worker-Csharp,我试图让我的程序在后台单独的BackGroundWorker上做一些工作。该操作非常有效,但myWorker_ProgressChanged
在lbl_status_totalFilesNotCurrent.Content
foreach循环myWorker_DoWork
内调用时未更新标签sendingWorker.ReportProgress(cnt);
的例外我无法弄清楚为什么这部分根据codeproject示例不起作用。
跟进问题...后台工作者是这类任务的首选方法,还是我应该使用任务? https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming。我开始意识到后台工作者已被弃用。
private BackgroundWorker myWorker = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
currentUser.name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
lbl_IndProj.MouseEnter += new MouseEventHandler(changeFontColor);
lbl_IndProj.MouseLeave += new MouseEventHandler(resetFontColor);
myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork);
myWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(myWorker_RunWorkerCompleted);
myWorker.ProgressChanged += new ProgressChangedEventHandler(myWorker_ProgressChanged);
myWorker.WorkerReportsProgress = true;
myWorker.WorkerSupportsCancellation = true;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
if (!myWorker.IsBusy)
{
myWorker.RunWorkerAsync(currentIndex);
}
}
protected void myWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker sendingWorker = (BackgroundWorker)sender;
Index ci = (Index)e.Argument;
int cnt = 0;
foreach (KeyValuePair<int, Project> project in currentIndex.projects)
{
foreach (KeyValuePair<int, IndexedDirectory> directory in project.Value.IndexedDirectories)
{
foreach (KeyValuePair<int, IndexedFile> indexedfile in directory.Value.IndexedFiles)
{
try
{
List<IndexedFile> ood = currentIndex.getOutOfDateIndexedFiles();
if (ood.Contains(indexedfile.Value))
{
cnt++;
indexedfile.Value.extractInfo();
lbl_status.Content = indexedfile.Value.LongName;
sendingWorker.ReportProgress(cnt);
}
}
catch { }
}
}
}
}
protected void myWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lbl_status_totalFiles.Content = currentIndex.getAllIndexedFiles().Count().ToString();
lbl_status_totalFilesNotCurrent.Content = currentIndex.getOutOfDateIndexedFiles().Count().ToString();
}
protected void myWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int cnt = e.ProgressPercentage;
int report = currentIndex.getOutOfDateIndexedFiles().Count() - cnt;
lbl_status_totalFilesNotCurrent.Content = report.ToString();
}