如何在BackgroundWorker的DoWork事件循环中向ProgressChanged上报文件名进度?
Solution Steps
1. Enable Progress Reporting for BackgroundWorker
First, ensure the BackgroundWorker allows progress reporting. Set this in the designer (toggle the WorkerReportsProgress property to true) or add this line to your form's constructor:
backgroundWorker1.WorkerReportsProgress = true;
2. Modify the SearcherCore Method to Report Progress
Update the recursive search method to pass the BackgroundWorker instance and report each found file:
private void SearcherCore(string sDir, BackgroundWorker worker) { try { foreach (var directory in Directory.GetDirectories(sDir)) { foreach (var filename in Directory.GetFiles(directory)) { using (var streamReader = new StreamReader(filename)) { var contents = streamReader.ReadToEnd().ToLower(); if (contents.Contains(SearchText)) { FilesFound.Add(filename); // Report the found filename to the ProgressChanged event worker.ReportProgress(0, filename); } } } SearcherCore(directory, worker); } } catch (System.Exception ex) { // Add exception handling logic here (e.g., logging) } }
3. Update the DoWork Event to Pass the BackgroundWorker
Modify the DoWork handler to pass the active BackgroundWorker instance to SearcherCore:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { if (!string.IsNullOrEmpty(textBoxSearchDirectory.Text)) { BackgroundWorker worker = sender as BackgroundWorker; SearcherCore(textBoxSearchDirectory.Text, worker); } }
4. Implement the ProgressChanged Event Handler
Add this handler to update your label with each found filename:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { string foundFile = e.UserState as string; // Update the label directly (this event runs on the UI thread automatically) labelFoundFile.Text = foundFile; }
Don’t forget to hook up the event to the BackgroundWorker (via designer or code):
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
Key Notes
- The first parameter of
ReportProgressis for percentage tracking (we used0here since we’re reporting individual files; adjust if you need overall progress metrics). - The
UserStateparameter carries the filename, which we extract in theProgressChangedhandler. - No manual thread marshaling (like
Invoke) is needed—ProgressChangedruns on the UI thread by default.
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

