首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 多執行緒委派模式:平行讀取多檔案並合併顯示於單一文字方塊

     編輯:關於C#

需求情境

指定目錄下存在多個小型文字檔,需以多執行緒方式平行讀取,將所有內容追加至同一個 TextBox 控制項中,不要求順序,僅需換行分隔。

核心技術點

  • Thread 建立工作執行緒
  • Control.InvokeRequired / Control.Invoke 跨執行緒安全存取 UI
  • 委派委派模式封裝檔案讀取邏輯
  • File.ReadAllText 一次性讀取檔案內容

完整實作程式碼

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 MultiThreadFileReader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelectFolder_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(InvokeThread);
                        t.Start(fi.FullName);
                    }
                }
            }
        }

        // 委派定義:對應檔案讀取方法簽章
        private delegate void ReadFileDelegate(object filePath);

        /// 
        /// 執行緒進入點:判斷是否需要跨執行緒叫用
        /// 
        private void InvokeThread(object filePath)
        {
            if (this.InvokeRequired)
            {
                // 非 UI 執行緒:透過 Invoke 切換至 UI 執行緒
                this.Invoke(new ReadFileDelegate(ReadFileContent), filePath);
            }
            else
            {
                // 已在 UI 執行緒:直接呼叫
                ReadFileContent(filePath);
            }
        }

        /// 
        /// 實際讀取檔案並追加至 TextBox
        /// 
        private void ReadFileContent(object filePath)
        {
            string path = filePath.ToString();
            string content = File.ReadAllText(path, Encoding.Default);
            this.textBox1.AppendText(content);
            this.textBox1.AppendText("\r\n");
        }
    }
}

關鍵細節解析

程式碼片段說明
Thread t = new Thread(InvokeThread); t.Start(fi.FullName);為每個 .txt 檔案建立獨立執行緒,傳入完整路徑
if (this.InvokeRequired)檢查目前執行緒是否為 UI 執行緒,避免跨執行緒操作例外
this.Invoke(new ReadFileDelegate(ReadFileContent), filePath);將檔案讀取工作排程至 UI 執行緒執行
File.ReadAllText(path, Encoding.Default)一次性讀取整個檔案,適用於小型文字檔
textBox1.AppendText(...)高效追加文字,自動捲動至末尾

進階優化建議

  1. 執行緒池:使用 ThreadPool.QueueUserWorkItem 或 Task.Run 避免建立過多執行緒
  2. 限制平行度:引入 SemaphoreSlim 或 Parallel.ForEach 控制同時讀取檔案數
  3. 非同步 I/O:.NET 4.5+ 可改用 File.ReadAllTextAsync 搭配 await 釋放執行緒
  4. 例外處理:在 ReadFileContent 加入 try-catch 避免單一檔案錯誤導致整體失敗

適用場景

  • 日誌檔案彙總分析
  • 批次匯入文字資料
  • 本地檔案內容快速搜尋與預覽

原文出處:https://www.zu14.cn/

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved