C#多線程delegate委託方式讀取多文件到同一個文本框顯示

今天,有個網友,提問:
指定目錄中有若干個很小的文本文件,現在需要使用多線程進行讀取。
一個文件一個線程或設置共有10個線程之類的方式都可以。
把讀取的文本全部追加到窗口中的指定編輯框中,只有一個編輯框,都寫在這個裏面,不分順序,換行即可。
我用委託的方式,寫了下面的解決方法:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace MultiThread
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
fbd.Description = "選擇要多線程讀取文件的路徑";
fbd.ShowNewFolderButton = false;
if (fbd.ShowDialog(this) == DialogResult.OK)
{
DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath);
foreach (FileInfo fi in di.GetFiles("*.txt"))
{
Thread t = new Thread(this.InvokeThread);
t.Start(fi.FullName);
}
}
}
}

private delegate void ReadFile(object filePath);

private void InvokeThread(object filePath)
{
if (this.InvokeRequired)
{
this.Invoke(new ReadFile(ReadFileContent), filePath);
}
else
{
ReadFileContent(filePath);
}
}


private void ReadFileContent(object filePath)
{
this.textBox1.AppendText(File.ReadAllText(filePath.ToString(), Encoding.Default));
this.textBox1.AppendText("\r\n");
}
}
}
 
 
放在這裏,給大家一個參考吧。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章