0

我需要并行执行 2 个任务。将在 GUI 中加载数据,直到那时我想在用户面前连续运行一个进度条。我尝试了 BackgroundWorker,但它给了我一些线程同步错误。有人可以建议我做同样的任何其他最佳方式。

代码: backgroundWorker1 初始化:

        backgroundWorker1 = new BackgroundWorker();
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

        if (backgroundWorker1.IsBusy != true)
        {
            backgroundWorker1.RunWorkerAsync();
        }

以下行出现错误:

    XmlDocumentHierarchy _remoteObj = new XmlDocumentHierarchy(comboBox2.Text, "username", "password");

是:

   "Cross-thread operation not valid: Control 'comboBox2' accessed from a thread other than the thread it was created on."
4

2 回答 2

0

如果您需要从 BackgroundWorker 线程访问 GUI 线程,您可以轻松地在 GUI 线程中调用您的方法,如下所示:

    public Form1()
    {
        InitializeComponent();

        Thread thr = new Thread(new ThreadStart(BackGroundThread));
        thr.Start();
    }

    void BackGroundThread() 
    {
        for (int i = 0; i < 100; i++) 
        {
            // The line below will be run in the GUI thread with no synchronization issues
            BeginInvoke((Action)delegate { this.Text = "Processed " + i.ToString() + "%"; });                
            Thread.Sleep(200);
        }
    }
于 2013-05-22T20:28:26.917 回答
0

您正在尝试访问comboBox2.TextGUI 线程(后台工作线程)以外的线程。如果您在后台工作线程中仅使用一个属性,则可以将“comboBox2.Text”传递给后台工作方法:

if (backgroundWorker1.IsBusy != true)
{
    backgroundWorker1.RunWorkerAsync(comboBox2.Text);
}

backgroundWorker1_DoWork程序中,您可以通过以下方式读取属性:

void backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e)
{
    String comboBoxText = (String)e.Argument;
    XmlDocumentHierarchy _remoteObj = new XmlDocumentHierarchy(comboBoxText, "username", "password");
}

如果您从 GUI 控件访问多个属性,您可以创建简单的类来将所有必要的数据传递给您的后台工作方法。

于 2013-05-23T14:09:09.660 回答