无效的跨线程访问后台工作程序错误c#

时间:2015-02-19 03:01:04

标签: c# multithreading winforms backgroundworker

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Threading;

namespace SRS
{
    public partial class excelimport : Form
    {
        public excelimport()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfiledialog1 = new OpenFileDialog();

            if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBox1.Text = openfiledialog1.FileName;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

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

        DataTable mysource;
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                string pathconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + textBox1.Text + " ;Extended Properties=\"Excel 12.0 Xml;HDR=YES;\";";
            OleDbConnection conn = new OleDbConnection(pathconn);

            OleDbDataAdapter mydatapter = new OleDbDataAdapter("select * from [" + textBox2.Text + "$]", conn);
            DataTable dt = new DataTable();

            mydatapter.Fill(dt);
                    datagridview1.datasource=dt;
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress((i * 10));
                }
            }


        }


        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.tbprogress.Text = (e.ProgressPercentage.ToString() + "%");
        }

        private delegate void tododelegate();

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.tbprogress.Text = "Canceled!";
            }

            else if (!(e.Error == null))
            {
                this.tbprogress.Text = ("Error: " + e.Error.Message);
            }

            else
            {
                this.tbprogress.Text = "Done!";
            }
        }

        private void excelimport_Load(object sender, EventArgs e)
        {
        }


    }
}

我收到了错误信息:

datagridview1.datasource = DT;

我试图像这样改变代码:

private DataTable loadingtable()
        {
            string pathconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + textBox1.Text + " ;Extended Properties=\"Excel 12.0 Xml;HDR=YES;\";";
            OleDbConnection conn = new OleDbConnection(pathconn);

            OleDbDataAdapter mydatapter = new OleDbDataAdapter("select * from [" + textBox2.Text + "$]", conn);
            DataTable dt = new DataTable();

            mydatapter.Fill(dt);

            return dt;
        }

并在加载事件dataGridView1.DataSource = mysource;

并在bw worker mysource = loadingtable();

然后没有错误,但是加载数据需要永远。

3 个答案:

答案 0 :(得分:1)

您无法在非UI线程上更新UI控件。

试试这个:

datagridview1.Invoke(() => datagridview1.datasource = dt);

答案 1 :(得分:1)

当您执行此操作时,您正在从后台工作者修改GUI(这是禁忌):datagridview1.datasource=dt;

查看使用InvokeRequiredInvoke的示例,以说明如何在事件调度线程上为您执行某些代码。

答案 2 :(得分:1)

BackgroundWorker允许您在UI的单独线程中运行一段代码,因此您不会锁定程序。需要注意的是,代码无法直接触及UI线程。您正在尝试从单独的线程更新控件,因此您将获得异常。

您已经订阅并正在使用ProgressChanged事件,因此请充分利用它。它在UI线程上运行。

worker.ReportProgress(i * 10, dt);

...

private void backgroundWorker1_ProgressChanged(object sender,
                                               ProgressChangedEventArgs e)
{
    this.tbprogress.Text = (e.ProgressPercentage.ToString() + "%");

    dataGridView1.DataSource = (DataTable)e.UserState;
}

仅供参考,您在循环中分配DataSource,因此每次迭代都会覆盖以前的DataSource。你可能想要仔细检查你的逻辑。

此外,您还有语法错误。它是DataSource,而不是datasource