3

在我的应用程序中,我在添加到我的列表框之前通过打开 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 完成然后才打开新的?

4

2 回答 2

9

据我了解,您只希望同时启动单个后台工作人员。如果是这样,那么试试这个(基于System.Threading.AutoResetEvent

//introduce additional field
private AutoResetEvent _workerCompleted = new AutoResetEvent(false);
//modify StartBackgroundFileChecker
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();
   //new code - wait for completion
   _workerCompleted.WaitOne();
}
//add completion notification to backgroundWorker_RunWorkerCompleted
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (Interlocked.Decrement(ref numWorkers) == 0)
    {
        //update my UI
    }

    //new code - notify about completion
    _workerCompleted.Set();
}

在该解决方案中,您的后台线程将一一启动新的 BackgroundWorker - 这可能不是最佳的(您可以完全避免 BackgroundWorker,只需通过threadStart委托中的 Dispatch 更新 UI)

在我看来,最好控制并行线程的数量,并且仍然在多个但数量有限的线程中处理文件。

这是替代解决方案(基于 System.Threading.Tasks 命名空间):

 private void btnAddDir_Click(object sender, EventArgs e)
 {
   var selectedPath = folderBrowserDialog1.SelectedPath;
   Task.Factory.StartNew(() =>
        {
           
            var files = Directory.EnumerateFiles(selectedPath, "*.*", SearchOption.AllDirectories);

            Parallel.ForEach(files,
                             new ParallelOptions
                             {
                                     MaxDegreeOfParallelism = 10 // limit number of parallel threads here 
                             },
                             file =>
                             {
                                 //process file here - launch your process
                             });
        }).ContinueWith(
            t => { /* when all files processed. Update your UI here */ }
            ,TaskScheduler.FromCurrentSynchronizationContext() // to ContinueWith (update UI) from UI thread
        );
}

您可以根据您的特定需求调整此解决方案。

使用的类/方法(请参阅 MSDN 以供参考):

  • 任务
  • TaskScheduler.FromCurrentSynchronizationContext
  • Parallel.ForEach 方法(IEnumerable、ParallelOptions、Action)
于 2013-05-28T12:01:15.307 回答
0

也许是这样的,而不是 foreach 保留文件列表,完成后只需获取第一个元素并更新您的列表

private List<string> _files;

private void btnAddDir_Click(object sender, EventArgs e)
{
    try
    {
        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
        {

            _files = new List<string>(SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories));

            Interlocked.Increment(ref numWorkers);
            var file = _files.FirstOrDefault();
            if(file != null)
                StartBackgroundFileChecker(file);
        }
    }
    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
        _files = _files.Skip(1);
        var file = _files.FirstOrDefault();
        if(file != null)
            StartBackgroundFileChecker(file);
    }
}
于 2013-05-28T10:51:36.773 回答