将数据导入datagridview冻结ui

时间:2019-03-25 16:29:18

标签: c# datagridview

我正在尝试将文本文件数据导入数据gridview,但是gridview冻结了ui。

我尝试使用backgroundworker,但是冻结了。文件大小甚至不到1 mb。

public async Task ReadDataToDataGridView() {
 await Task.Yield();
 Invoke(new Action(async delegate() {
  await Task.Yield();
  int row = 0;
  OpenFileDialog openFile = new OpenFileDialog();
  openFile.DefaultExt = "txt";
  openFile.Filter = "Text Files (*txt)|*ini|All files (*.*)|*.*";
  openFile.AddExtension = true;
  openFile.ShowDialog();
  string path = openFile.FileName;
  using(FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  using(BufferedStream bs = new BufferedStream(fs))
  using(StreamReader sr = new StreamReader(bs)) {
   string line;
   while ((line = sr.ReadLine()) != null) {
    try {
     // Thread.Sleep(1000);
     dataGridView1.Invoke(new Action(delegate() {
      dataGridView1.Rows.Add();
      dataGridView1.Rows[row++].Cells[0].Value = line.Split(':')[0];
      dataGridView1.Refresh();
      //dataGridView1.Rows[row].Cells[1].Value = line.Split(':')[1];
     }));
    } catch {

    }
   }
  }
 }));
}

0 个答案:

没有答案