在运行时更新数据源时,如何避免控件会冻结



我在Winforms应用程序中工作,并在我的应用程序中使用了DataGridView控件。最初,我在其中加载了10000行和50列。我的情况是在特定时间间隔(使用计时器)更新数据源。

问题:在更新数据源时,网格在执行操作(Cell_Click,Scrolling等)时已被冻结/帮派。

如何解决这个问题?有工作吗?请给我你的想法。

这是我到目前为止的代码:

private void timer1_Tick(object sender, EventArgs e)
    {
        //try
        {
            timer.Stop();
            for (int i = 0; i < 10000; i++)
            {
                var row = r.Next() % 10000;
                for (int col = 1; col < 10; col++)
                {
                    var colNum = r.Next() % 55;
                    if (table != null)
                        table.Rows[row][colNum] = "hi";// r.Next().ToString();
                }
            }
            table.AcceptChanges();
            timer.Start();
        }
    }

这是一个样本输出:

[https://drive.google.com/open?id=0b9mogv1fot-tq1bnzwtnrktxexc]

谢谢。

解决方案之一是在如此长的运行操作中调用Application.DoEvents()。这是样本

private void timer1_Tick(object sender, EventArgs e)
{
    //try
    {
        timer.Stop();
        for (int i = 0; i < 10000; i++)
        {
            var row = r.Next() % 10000;
            for (int col = 1; col < 10; col++)
            {
                var colNum = r.Next() % 55;
                if (table != null)
                    table.Rows[row][colNum] = "hi";// r.Next().ToString();
            }
            Application.DoEvents(); //add this line
        }
        table.AcceptChanges();
        timer.Start();
    }
}

另一个解决方案是将您的长期运行任务移至单独的线程。

尝试使用backgrounworker。

背景工作人员是system.componentmodel中的助手类 管理工作线程的命名空间。它可以被视为 EAP的通用实现(基于事件的异步模式),并提供以下 功能:

  • 合作取消模型

  • 当工人完成

  • 时,可以安全更新WPF或Windows表单控件的能力
  • 将例外事件的异常转发
  • 报告进度的协议
  • IComponent的实现,允许将其放在Visual Studio的设计师

波纹管您可以找到一个例子,请将其调整到计时器:

class Program
{
  static BackgroundWorker _bw = new BackgroundWorker();
  static void Main()
  {
    _bw.DoWork += bw_DoWork;
    _bw.RunWorkerAsync ("Message to worker");
    Console.ReadLine();
  }
  static void bw_DoWork (object sender, DoWorkEventArgs e)
  {
    // This is called on the worker thread
    Console.WriteLine (e.Argument);        // writes "Message to worker"
    // Perform time-consuming task...

           //update your grid
            for (int i = 0; i < 10000; i++)
            {
                var row = r.Next() % 10000;
                for (int col = 1; col < 10; col++)
                {
                    var colNum = r.Next() % 55;
                    if (table != null)
                        table.Rows[row][colNum] = "hi";r.Next().ToString();
                }
            }
            table.AcceptChanges();
  }
}

最新更新