Search code examples
c#winformsbackgroundworker

How can I display each thread in another label?


In the button1 click event I create a number of backgroundworkers that depend on how many items I selected in the listbox:

    private void button1_Click(object sender, EventArgs e)
    {
        // For each item selected in the listbox
        foreach (var item in listBox1.SelectedItems)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += backgroundWorker1_DoWork;
            worker.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
            object argument = item;
            worker.RunWorkerAsync(argument);
        }

        offlineOnline = false;
        init();
        button1.Enabled = false;
        this.Text = "Processing...";
        label6.Text = "Processing...";
        label6.Visible = true;
        button2.Enabled = false;
        checkBox1.Enabled = false;
        checkBox2.Enabled = false;
        numericUpDown1.Enabled = false;
        button3.Enabled = true;
        button6.Enabled = false;
        button4.Enabled = true;
        button5.Enabled = false;
        listBox1.Enabled = false;
    }
}

Then in the DoWork event I'm using the threads like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    object input = e.Argument;
    string f = GetUrl(input);
    this.Invoke(new MethodInvoker(delegate { label2.Text = "Website To Crawl: "; }));
    this.Invoke(new MethodInvoker(delegate { label4.Text = f; }));
    if (offlineOnline == true)
    {
        offlinecrawling(f, levelsToCrawl, e);
    }
    else
    {
        webCrawler(f, levelsToCrawl, e);
    }
}

The problem is that in the label4.Text I will see the last URL from the two threads. I want to have, for example, two different labels. Each one will show the other thread. For example, in label4.Text there will be www.cnn.com and in label7.Text will be www.cnet.com.

I don't understand how to catch or get each thread URL and put it in a label?


Solution

  • Yes, first I'd recommend to rename your controls - as @Henk_Holterman suggested. You can for example pass as Argument not only input, but some class / pair with input + label to be updated. Then, update your delegates to use specified labels.