在我的应用程序中,我在将文件添加到我的 Listbox 之前通过打开 Wireshark 进程来检查它们。这是“添加目录”单击事件,它获取根文件夹并检查此文件夹及其子文件夹中的所有文件:
private void btnAddDir_Click(object sender, EventArgs e)
{
try
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
ThreadStart threadStart = delegate
{
foreach (string file in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
{
Interlocked.Increment(ref numWorkers);
StartBackgroundFileChecker(file);
}
};
Thread thread = new Thread(threadStart);
thread.IsBackground = true;
thread.Start();
}
}
catch (Exception)
{ }
}
private void StartBackgroundFileChecker(string file)
{
ListboxFile listboxFile = new ListboxFile();
listboxFile.OnFileAddEvent += listboxFile_OnFileAddEvent;
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s3, e3) =>
{
//check my file
};
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.RunWorkerAsync();
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Interlocked.Decrement(ref numWorkers) == 0)
{
//update my UI
}
}
当我检查这个文件时,我打开了Wireshark
进程,所以如果我选择有许多文件的文件夹,会打开许多Wireshark
进程,这会占用很多内存。如何等待我的BackgroundWorker完成后再打开新的进程?