目錄下大量小文本文件,需多線程並發讀取並追加顯示到單一 `TextBox`,使用委托 `Invoke` 確保線程安全。
public partial class Form1 : Form {
private delegate void ReadFileDelegate(object filePath);
private void btnStart_Click(object sender, EventArgs e) {
using (var fbd = new FolderBrowserDialog()) {
if (fbd.ShowDialog() == DialogResult.OK) {
var di = new DirectoryInfo(fbd.SelectedPath);
foreach (var fi in di.GetFiles("*.txt")) {
var t = new Thread(InvokeThread);
t.Start(fi.FullName);
}
}
}
}
private void InvokeThread(object filePath) {
if (this.InvokeRequired)
this.Invoke(new ReadFileDelegate(ReadFileContent), filePath);
else
ReadFileContent(filePath);
}
private void ReadFileContent(object filePath) {
textBox1.AppendText(File.ReadAllText(filePath.ToString(), Encoding.Default));
textBox1.AppendText("\r\n");
}
}
// .NET 4.5+ 推薦
var files = Directory.EnumerateFiles(path, "*.txt");
await Task.WhenAll(files.Select(f => Task.Run(() => {
string content = File.ReadAllText(f);
this.Invoke(() => textBox1.AppendText(content + "\r\n"));
})));