如何在C#中将数组作为doWork的参数传递

时间:2011-12-23 14:54:52

标签: c# backgroundworker

我需要在readstream函数中使用comboBox1.text和comboBox2.Text等表单控件,这会传递错误消息(翻译自德语):

  

控制元素comboBox1 / comboBox2的访问来自另一个线程而不是在其中创建它的线程!!!

我需要的是将这些控件传递给readstream函数,但我不知道究竟是什么。

代码

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

2 个答案:

答案 0 :(得分:9)

在致电worker.RunWorkerAsync();之前,请执行以下操作:

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

然后,在ReadStream(...)

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

答案 1 :(得分:3)

尝试使用此代码将数组作为参数传递:

worker.RunWorkerAsync(array);

使用此代码获取此数组:

doWorkEventArgs.Argument