Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        }
    }
}
like image 848
user1096252 Avatar asked Dec 16 '22 05:12

user1096252


2 Answers

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];
like image 76
Adam Avatar answered Dec 18 '22 18:12

Adam


Try this code to pass array as parameter:

worker.RunWorkerAsync(array);

Use this code to get this array:

doWorkEventArgs.Argument
like image 23
Kashif Khan Avatar answered Dec 18 '22 19:12

Kashif Khan