C#:txt内容显示到dataGridView程序假死问题:

2025-03-22 19:37:46
推荐回答(5个)
回答1:

采用多线程实现吧。
首先说一下,如果使用his.dataGridView1.DataSource = dt;这样的赋值方式,即使多线程时,在赋值也会有白屏现象。
在我的机器上面测试51万的数据,装载文件需要6秒,his.dataGridView1.DataSource = dt;这个赋值语句需要3秒。

可使用his.dataGridView1.Rows.AddRange()方法。
具体的代码见下面:
private void button1_Click(object sender, EventArgs e)
{
string filePath = GetOpenFilePath();
Thread thread = new Thread(new ParameterizedThreadStart(SetDataGridViewDataSource));
thread.Start(filePath);
}
private string GetOpenFilePath()
{
string filePaht = string.Empty;
using (OpenFileDialog dlgText = new OpenFileDialog())
{
dlgText.Filter = "文本文件|*.txt";
if (dlgText.ShowDialog() == DialogResult.OK)
{
filePaht = dlgText.FileName;
}
}
return filePaht;
}

private void SetDataGridViewDataSource(object filePath)
{
System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();

st.Start(); //开始计时

//新建一个datatable用于保存读入的数据
DataTable dt = new DataTable();
//给datatable添加三个列
dt.Columns.Add("帐号", typeof(String));
dt.Columns.Add("密码", typeof(String));
dt.Columns.Add("备注", typeof(String));
//读入文件
using (StreamReader reader = new StreamReader(filePath.ToString(), Encoding.Default))
{
//循环读取所有行
while (!reader.EndOfStream)
{
//将每行数据,用-分割成3段
string[] data = reader.ReadLine().Replace("----", "-").Split('-');
//新建一行,并将读出的数据分段,分别存入3个对应的列中
DataRow dr = dt.NewRow();
dr[0] = data[0];
dr[1] = data[1];
dr[2] = data[2];
//将这行数据加入到datatable中
dt.Rows.Add(dr);
}
}
st.Stop();
Console.WriteLine("第一次计时:" + st.ElapsedMilliseconds);

st.Reset();
st.Start();
//将datatable绑定到datagridview上显示结果
this.Invoke(new MethodInvoker(delegate() { this.dataGridView1.DataSource = dt; }));
//在此处可将数据进行分批赋值,一次赋值1000条
//this.dataGridView1.Rows.AddRange();
st.Stop();
Console.WriteLine("第二次计时:" + st.ElapsedMilliseconds);
}

回答2:

你一次显示一万条以上的数据啊,不符合实际要求,dataGridView翻页,txt也不要一次性读入,每次记录读取位置,只读取需要的,对性能有要求还可以使用缓存,一个文本文件太大的话对内存要求也很高的

回答3:

楼主,从你贴的代码上看来,并没有什么明显问题。如果数据量大造成假死的话,你可以弄个进度条的效果解决呀。

回答4:

解决假死要开一个线程来 读入文件 在读取数据线程里要使用委托 这样才能让UI(界面线程显示)
这样UI线程压力就小了,不会假死了。

回答5:

弄个翻页,分页显示内容吧。估计内容太多造成的。