使用多线程实时更新DataGridVIew

时间:2017-04-05 05:47:09

标签: c# multithreading datagridview

我有一个带有product_list表的数据库

$code

然后我有两个Windows窗体应用程序。每个应用程序都在单独的项目中。

  1. 第一个应用程序是将数据插入到查询为+----+-------------+-------+-------+ | id | description | price | Stock | +----+-------------+-------+-------+ | 1 | Item 1 | 1.50 | 5 | +----+-------------+-------+-------+
  2. 的表中
  3. 第二个应用是使用datagridview实时查看表。 我有一个数据库对象,并有一个函数名称GetTable()返回一个DataTable。
  4. 这是返回DataTable的数据库对象的代码。

    INSERT INTO product_list (description, price, stock) VALUES ('Item 2', 2.00, 10)

    这里是多线程的代码

         public DataTable GetTable()
         {
            DataTable table = new DataTable();
    
            try
            {
                MySqlDataAdapter daTable = new MySqlDataAdapter(this.query, this.conn);
                daTable.Fill(table);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    
            return table;
         }
    

    当我运行visual studio时,会发出InvalidOperationException。

1 个答案:

答案 0 :(得分:1)

您可以使用控件的InvokeRequired属性。试试这段代码。

DataTable inventoryTable;
inventoryDB inventoryDB;

Thread updateDataGridView;

public Form1()
{
    InitializeComponent();
    inventoryDB = new inventoryDB();
}

private void Form1_Load(object sender, EventArgs e)
{
    inventoryDB.SetQuery("SELECT id AS ID, description as Description, price as Price, stock as Stock FROM `product_list");
    inventoryTable = inventoryDB.GetTable();

    this.dataGridView1.DataSource = inventoryTable;

    this.updateDataGridView = new Thread(new ThreadStart(this.RealTimeData));
    this.updateDataGridView.Start();
}

private void RealTimeData() {
    testTable = inventoryDB.GetTable();
    this.SetDataSourceInGridView(testTable);
}

// This delegate enables asynchronous calls for setting  
// the datasource property on a GridView control.  
delegate void GridViewArgReturningVoidDelegate(DataTable testTable); 

private void SetDataSourceInGridView(DataTable testTable)
{
    // InvokeRequired required compares the thread ID of the  
    // calling thread to the thread ID of the creating thread.  
    // If these threads are different, it returns true.  
    if (this.dataGridView1.InvokeRequired)  
    {     
        GridViewArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetDataSourceInGridView);  
        this.Invoke(d, new object[] { testTable });  
    }  
    else  
    {  
        this.dataGridView1.DataSource = testTable;
        this.dataGridView1.Update();
        this.dataGridView1.Refresh();  
    }  
}