c# - 如何在 C# 中将数组作为参数传递给 doWork

标签 c# backgroundworker

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

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

我需要的是将这些控件传递给 readstream 函数,但我不知 Prop 体怎么做。

代码

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

最佳答案

在调用 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];

关于c# - 如何在 C# 中将数组作为参数传递给 doWork,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617398/

相关文章:

c# - 调试器没有跳过/进入异步/等待

c# - 将类的可空双属性序列化为 Xml 文本

.net - COM 对象 - 线程 - .net

C#后台 worker ,winform。 "Cross-thread operation not valid:"

c# - 是否可以防止 Visual Studio 在 BackgroundWorker.DoWork 内出现异常时中断

c# - 如何在 C# 中让代码等待几毫秒?

c# - 更新多行

c# - Task.WaitAll 因异步/等待任务而挂起

c# - 从文本文件中读取行跳过读取行

c# - 当我需要抓取网站时,我应该使用 BackgroundWorker 还是 Threads?