C# – Wait until the BackgroundWorker finish in order to open new BackgroundWorker

c++winforms

In my application i am checking my files by open Wireshark process before add to my Listbox.
this is Add Directory click event who take root folder and checking all this files inside this folder and sub folders:

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
    }
}

When i am checking this file i am open Wireshark process so if i choose folder with many files, many Wireshark processes opned and this take a lot on memory,
how can i wait until my BackgroundWorker finish and only then open new one ?

Best Solution

As I understand you want only single background worker launched at time. If so, then try this (based on 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();
}

In that solution your background thread will start new BackgroundWorker one by one - this can be not optimal (you could avoid BackgroundWorker at all and simply update UI via Dispatch in threadStart delegate)

In my opinion better to control number of parallel threads and still process files in multiple but limited numbers of threads.

Here is the alternative solution (based on System.Threading.Tasks namespace):

 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
        );
}

You can tweak this solution for your specific needs.

Used classes/methods (see MSDN for reference):

  • Task
  • TaskScheduler.FromCurrentSynchronizationContext
  • Parallel.ForEach Method (IEnumerable, ParallelOptions, Action)
Related Question