通過使用這樣的:
string[] text = System.IO.File.ReadAllLines(file);
listBox1.Items.AddRange(text);
,而不是這樣的:
string[] text = System.IO.File.ReadAllLines(file);
foreach (string line in text)
{
listBox2.Items.Add(line);
}
你將加快執行速度,因爲你至少10-15倍不會使每個商品插入的listBox失效。我用幾千行測量過。
如果文本的行數太多,瓶頸也可能是ReadAllLines
。即使我不知道爲什麼你會插入這麼多的線,用戶是否能夠找到他/她需要的線?
編輯 OK那麼我建議你使用BackgroundWorker的,這裏是代碼:
首先你初始化的BackgroundWorker:
BackgroundWorker bgw;
public Form1()
{
InitializeComponent();
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
}
然後你把它在你的方法:
private void button1_Click(object sender, EventArgs e)
{
if (!bgw.IsBusy)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Text Files|*.txt";
openFileDialog1.Title = "Select a Text file";
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
listView1.BeginUpdate();
bgw.RunWorkerAsync(file);
}
}
else
MessageBox.Show("File reading at the moment, try later!");
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
listView1.EndUpdate();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
string fileName = (string)e.Argument;
TextReader t = new StreamReader(fileName);
string line = string.Empty;
while ((line = t.ReadLine()) != null)
{
string nLine = line;
this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(nLine); });
}
}
這將增加每個行,當它讀取它,你將有響應性的UI,並且線條不會影響列表框中它finishe前s loading。
4-5兆字節文件中有多少行? – 3aw5TZetdf
崩潰時的錯誤是什麼? –
我可能是錯的,但如果我沒記錯的話,列表框上有64k的限制 – DarkSquirrel42