0
votes

I am working on an application that searches the files in the directory provided using background worker... the problem is with the backgroundWorker1.RunWorkerAsync();

following is my code when i am trying to give multiple paths for searching the file i type in the textbox

private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyValue == 13)
    {
        foreach (string s in listBox1.Items)
        {
            DirectoryInfo deer = new DirectoryInfo(s);
            toolStripButton2.Visible = true;
            //listView1.Items.Clear();
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync(deer);
            }
            else
                MessageBox.Show("Can't run the worker twice!");
            // backgroundWorker1.RunWorkerAsync(deer);
        }
    }
    listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
    listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
}

and i get the following error

This BackgroundWorker is currently busy and cannot run multiple tasks concurrently. please help me out..

2
Have you considered using a (blocking) queue for your worker, in which you enqueue the "deer"? - Alex

2 Answers

0
votes

Not sure what you're trying to achieve here.

1) If you wish to run multiple tasks concurrently on different threads (i.e. to process each one of the items in the listBox1.Items), you will have to create separate threads or tasks to do so, and not use the same background worker.

2) If you simply wish to handle the overall processing of these items in the background without affecting (blocking) the UI you will need to use one background worker and pass it the entire collection.

In any case, the current code should not throw the error, unless you comment out the mbox and uncomment the other backgroundWorker1.RunWorkerAsync(deer);. If you do that, then you're basically trying to start the same thread before it finished it's previous work. If you don't do that, you're basically skipping items in the list from being processed until the thread becomes available again.

A general example of the 1st should look like this:

foreach (string s in listBox1.Items)
{
    DirectoryInfo deer = new DirectoryInfo(s);
    toolStripButton2.Visible = true;            
    Task.Run(() => TheDoWorkMethodYouUsed(deer);
}

A general example of the 2nd would be to modify your do work method to run over the entire collection, and passing that collection:

if (e.KeyValue == 13)
{
    backgroundWorker1.RunWorkerAsync(listBox1.Items);        
}

And in the DoWork method:

foreach (string s in passedList)
{
    DirectoryInfo deer = new DirectoryInfo(s);
    // continue with normal processing of the method
}