天天看點

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");
        }
    }
}