【问题标题】:Populating data on Gridview using Thread使用 Thread 在 Gridview 上填充数据
【发布时间】:2011-03-09 14:38:04
【问题描述】:

我在加载时的表单中有一个 winform Datagridview 控件,我填充了近 1000 条甚至更多的记录。每隔几秒钟就会从我的 sql 服务器中获取数据,并且必须在网格上填充数据。我不希望我的网格冻结。请帮我解决这个问题.....

【问题讨论】:

    标签: multithreading datagridview using


    【解决方案1】:
    1. 将人口代码放入方法中。
    2. 在方法中放置一个循环,以便在布尔变量设置为 TRUE 之前一直运行。
    3. 创建一个调用该方法的线程对象。
    4. 启动线程对象。
    5. 当方法需要更新网格时,必须使用DELEGATE和DataGridView.Invoke方法来更新网格;否则会出现线程错误。
    6. 当您想取消线程时,请将变量设置为 TRUE。

    【讨论】:

      【解决方案2】:

      只需使用计时器,当它滴答作响时创建一个新线程并更新DataGrid

      Windows 窗体和 TPL(.NET Framework 4 和 3.5)示例。

      初始化定时器:

      this.timer = new Timer() { Interval = 2000 };
      this.timer.Tick += OnFetch;
      this.timer.Start();
      

      管理 Tick 事件:

      private void OnFetch(object sender, EventArgs e)
      {
          Task.Factory.StartNew(() =>
          {
              // Get the data from your db
              var data = GetDbData();
              foreach (MyElement row in data)
              {
                  if (dataGridView1.InvokeRequired)
                  {
                      dataGridView1.Invoke(new Action(() =>
                      {
                          // Add the row
                      }));
                  }
              }
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 1970-01-01
        • 1970-01-01
        • 2014-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多