1

我有一个简单的测试类:

public partial class TEST_CLASS
{
    public string IP { get; set; }
    public int PORT { get; set; }
}

iList<TEST_CLASS> MY_CLASS = new List<TEST_CLASS>();

我有以下代码将类绑定到 DGV:

        TEST_CLASS n = new TEST_CLASS();
        MY_CLASS.Add(n);


        grid_nodes.DataSource = MY_CLASS;

        Thread t = new Thread(set1);
        t.Start();

        Thread t2 = new Thread(set2);
        t2.Start();

以及将类更新为随机值以进行测试的线程:

    public void set1()
    {
        while (true)
        {
            Random r = new Random();
            MY_CLASS[0].IP = r.Next(999900);
            Thread.Sleep(100);
        }
    }

    public void set2()
    {
        while (true)
        {
            Random r = new Random();
            MY_CLASS[0].PORT = r.Next(999900);
            Thread.Sleep(100);
        }
    }

问题是 DGV 没有正确更新。每次单击单元格时,我只会看到更新。

我将有数千行和单独的线程更新 MY_CLASS,我需要在 DGV 上“实时”显示更改。

据我了解,每次更新课程时都需要调用 DGV.Update() 吗?这样做的最佳方法是什么,因为我将有成千上万的线程不断更新类?谢谢!

4

2 回答 2

2

好的,所以我只是在计时器中添加了以下代码,并使其在某些条件下触发,效果很好:

            grid.DataSource = null;
            grid.DataSource = MY_LIST;
            grid.Invalidate();
于 2012-04-17T14:56:48.677 回答
0

If you use BindingList instead of List, and make your TEST_CLASS implement INotifyPropertyChanged, then the grid will update itself. However you will need to ensure that only happens on the UI thread by some form of marshalling (like SynchronizationContext or grid.Invoke()).

于 2012-04-24T00:50:31.960 回答