通过线程加载数据

时间:2011-04-08 03:35:10

标签: c#

C#:

我想从数据库加载大数据,并在加载进度中,我希望显示可用于DatagridView。我使用IDataReader和BackgroundWorker。但在艰难尝试某种方式,我得到错误。 我希望当Execute Script到服务器时,数据接收将具有Schema信息,并且它将动态创建DatagridView的结构,并且从该结构开始,可用数据将逐行添加到网格中,用户可以看到此更改。 我的代码如下,但错误。任何答案都可以帮助我处理,我非常感谢!

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.SqlClient;

namespace WindowsFormsApplication1
{
    partial class Form1
    {

        string conectionString = "";

        IDbConnection connection;

        BackgroundWorker worker;

        BindingSource binding;

        IDbCommand GetExecuteCommand()
        {
            string commandText = "select * from dbo.B20DmBp";
            SqlCommand command = new SqlCommand();
            command.Connection = (SqlConnection)this.connection;
            command.CommandText = commandText;
            command.CommandType = CommandType.Text;
            return command;
        }

        public Form1()
        {
            InitializeComponent();
            Initialize();
            RegisterHandler();
        }

        void Initialize()
        {
            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
            worker.WorkerReportsProgress = true;

            binding = new BindingSource();
            this.dataGridView1.DataSource = binding;
            connection = new SqlConnection(conectionString);
        }

        void RegisterHandler()
        {
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            DataTable table = this.binding.DataSource as DataTable;

            IDataReader reader = e.UserState as IDataReader;

            table.Rows.Add(this.BuildDataRow(reader));

            this.binding.ResetBindings(false);
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            IDbCommand command = e.Argument as IDbCommand;

            BackgroundWorker worker2 = sender as BackgroundWorker;

            try
            {
                command.Connection.Open();
                IDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                        worker.ReportProgress(0, reader);
                    }
                }

                reader.Close();
                command.Connection.Close();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                command.Connection.Close();
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            throw new NotImplementedException();
        }

        void StartExecute()
        {
            this.binding.DataSource = new DataTable();

            this.worker.RunWorkerAsync(this.GetExecuteCommand());
        }

        void CancelExecute()
        {
            if (this.worker.WorkerSupportsCancellation)
            {
                this.worker.CancelAsync();
            }
        }

        DataRow BuildDataRow(IDataReader reader)
        {
            DataTable table = this.binding.DataSource as DataTable;

            if (table.Columns.Count == 0)
            {
                foreach (DataRow row in reader.GetSchemaTable().Rows)
                {
                    string columnName = row["ColumnName"].ToString();
                    table.Columns.Add(columnName);
                }

                this.binding.ResetBindings(true);
            }

            DataRow row2 = table.NewRow();

            foreach (DataRow row in reader.GetSchemaTable().Rows)
            {
                string columnName = row["ColumnName"].ToString();
                row2[columnName] = reader[columnName];
            }

            return row2;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.StartExecute();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.CancelExecute();
        }



















        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGridView1
            // 
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(35, 26);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(240, 150);
            this.dataGridView1.TabIndex = 0;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(35, 194);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(127, 194);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 2;
            this.button2.Text = "button2";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(323, 262);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.dataGridView1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
    }
}

1 个答案:

答案 0 :(得分:1)

是否发生了跨线程访问错误? 如果是,您可以按主题解析:http://msdn.microsoft.com/en-us/library/ms171728%28VS.80%29.aspx