Search code examples
c#backgroundworker

How to pass an array as a parameter for doWork in C#


I need to use form controls like comboBox1.text and comboBox2.Text inside the readstream function an this deliver an error message (translated from German):

The access of control element comboBox1/comboBox2 is from another thread rather than the thread in which it is created in !!!

What I need is to pass these controls to the readstream function, but I don't know how exactly.

Code

private void button1_Click(object sender, EventArgs e)
{
    BackgroundWorker worker = new BackgroundWorker;
    worker.WorkerReportsProgress = true;
    worker.ProgressChanged += ProgressChanged;
    worker.DoWork += ReadStream;

    //Need to pass the comoBox Texts from here!!!
    string start = comboBox1.Text;
    string end = comboBox2.Text;
    worker.RunWorkerAsync();
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    UpdateProgressBar(e.ProgressPercentage);
    comboBox1.Text = e.UserState.ToString();
}

private void ReadStream(object sender, DoWorkEventArgs doWorkEventArgs)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    string line;
    //And use the values here !!!!
    using (StreamReader sr = new StreamReader("file", System.Text.Encoding.ASCII))
    {
        while (!sr.EndOfStream)
        {
            line = sr.ReadLine();
            worker.ReportProgress(line.Length);
        }
    }
}

Solution

  • Before you call worker.RunWorkerAsync();, do this:

    string[] texts = new string[] {start, end};
    worker.RunWorkerAsync(texts);
    

    Then, in ReadStream(...)

    string[] extracted = (string[])doWorkEventArgs.Argument;
    string start = extracted[0];
    string end = extracted[1];