1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Windows.Forms; 8 using System.IO; 9 using System.Threading; 10 11 namespace MultiThread 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 private void button1_Click(object sender, EventArgs e) 21 { 22 using (FolderBrowserDialog fbd = new FolderBrowserDialog()) 23 { 24 fbd.Description = "选择要多线程读取文件的路径"; 25 fbd.ShowNewFolderButton = false; 26 if (fbd.ShowDialog(this) == DialogResult.OK) 27 { 28 DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath); 29 foreach (FileInfo fi in di.GetFiles("*.txt")) 30 { 31 Thread t = new Thread(this.InvokeThread); 32 t.Start(fi.FullName); 33 } 34 } 35 } 36 } 37 38 private delegate void ReadFile(object filePath); 39 40 private void InvokeThread(object filePath) 41 { 42 if (this.InvokeRequired) 43 { 44 this.Invoke(new ReadFile(ReadFileContent), filePath); 45 } 46 else 47 { 48 ReadFileContent(filePath); 49 } 50 } 51 52 private void ReadFileContent(object filePath) 53 { 54 this.textBox1.AppendText(File.ReadAllText(filePath.ToString(), Encoding.Default)); 55 this.textBox1.AppendText("\r\n"); 56 } 57 } 58 }
转载于:https://www.cnblogs.com/allyc/p/3304254.html