如何在C#中将数据从线程获取到UI(如何使用backgroundWorker)

时间:2013-07-31 06:41:40

标签: c# multithreading winforms datagridview backgroundworker

在我的应用程序中,我使用的是数据网格视图。要在数据网格视图中填充的数据位于另一个线程中。

如何从另一个线程获取数据到数据网格视图?我怎样才能使用后台工作者呢? (请在下面找到示例代码)

请帮忙。我是c#的新手。

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;

namespace ex1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        dataGridView1.Columns.Add("1", "Sno"); 
        dataGridView1.Columns.Add("2", "Time");
        dataGridView1.Columns.Add("3", "Name");
    }
public void button2_Click(object sender, EventArgs e)
{

    // Get data from MyThread and add new row to dataGridView1.

    //Like,
    dataGridView1.Rows.Add(sno,time,name); // strings from MyThread

}

#region EVENT THTEAD (RX)
    public void MyThread()
    {
        // Each time button2 press, took data from here and add that to dataGridView1 as a new row.

        String sno= "some value";
        String time="some value";
        String name="some value";

     }
    #endregion
}
}

1 个答案:

答案 0 :(得分:0)

如果要从MyThread()范围外部访问sno,time和name变量,则应将声明移动到外部范围。像这样:

String sno;
String time;        
String name;

public void MyThread()
    {
        // Each time button2 press, took data from here and add that to dataGridView1 as a new row.

        sno= "some value";
        time="some value";
        name="some value";

     }

要从另一个线程更新UI,您可以使用扩展方法创建此类:

 public static class ExtensionMethods
    {
        public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
        {
            if (@this.InvokeRequired)
            {
                @this.Invoke(action, new object[] { @this });
            }
            else
            {
                action(@this);
            }
        }
}

然后从你的其他“数据”线程中,你可以像这样使用它:

 this.InvokeEx(f => f.myTextBox.Text = "Some tekst from another thread");

但是您必须使用一些数据网格逻辑而不是此文本框示例来引入您自己的操作......这样的事情:

this.InvokeEx(f => f.dataGridView1.Rows.Add(sno,time,name));

如果你不熟悉这个,这里有一些关于扩展方法的信息:

http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx

以下是有关动作的一些信息:

http://msdn.microsoft.com/en-us/library/018hxwa8.aspx