RichTextBox to BackgroundWorker

本文关键字:BackgroundWorker to RichTextBox | 更新日期: 2023-09-27 17:49:18

如何将RichTextBox1的值抛出到C#中的BackgroundWorker

public void button4_Click(object sender, EventArgs e)
{
    if (String.IsNullOrEmpty(richTextBox1.Text.Trim())){
        MessageBox.Show("No value in RichTextBox?");
        return;
    }
    if (backgroundWorker1.IsBusy != true)
    {
        // Start the asynchronous operation.
        backgroundWorker1.RunWorkerAsync(richTextBox1);
    }

这是我的BackgroundWorker代码:

public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
    HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
    foreach (string vr in richTextBox1.Lines)
    {
    ⋮
    }
}

RichTextBox to BackgroundWorker

由于上面给出的原因,您不能传递RichTextBox,但您可以传递字符串数组,即RichTextBox。Lines属性并对其进行迭代。

private void button1_Click(object sender, EventArgs e)
{
    bg.RunWorkerAsync(richTextBox1.Lines);
}
void bg_DoWork(object sender, DoWorkEventArgs e)
{
    string[] lines = (string[])e.Argument;
    foreach(string vr in lines)
    {
    }
}
private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync(richTextBox1.Text);
    }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        string text = (string)e.Argument;
        MessageBox.Show(text);
    }

文本以对象e.argument的形式发送。要检索它,请将e.arguments转换回字符串(或字符串[]等,具体取决于您传递的内容(

通常只有主UI线程可以与窗体和控件交互。

考虑将它需要的所有数据传递给RunWorkerAsync方法——也许是RunWorkerAsync(richTextBox1.Lines.ToList())