標籤: w網智數位

在.Net 透過 Parallel 類別操控多任務平行作業(二)【軟體開發、軟體設計、系統開發、客製化軟體】

    這篇主要是再次講解 Parallel 類別並行作業的其他支援方法,主要是延續上一篇教學文章 3-1.透過 Parallel 類別操控多任務平行作業(一)。 

    這邊我將透過WPF專案實作一個使用 Parallel.ForEach 方法來支援的循環平行作業任務,它的概念就好比我們常在寫的 for(i=0;i<=10;i++)、或 foreach 迴圈,只是Parallel 類別是充分利用多個處理器、多個核心同時進行作業,執行速度當然效率就快很多。



步驟1:

在 Visual Studio 一樣建立一個WPF 專案

wpf

步驟2:

在 MainWindows.xmal 界面設計成如下結果

parellel

主要是使用了 3個 textbox 控制項,用於讓使用者輸入 資料夾路徑 、想建立的檔案數量、以及每個檔案的大小,再來使用一個 button 按鈕(開始執行 Parallel.Foreach 多任務運算), 來撰寫主要的 並行作業邏輯程式碼。


xaml 程式碼部分畫面
xaml2


步驟3:

在 Button.Click 事件撰寫主要程式碼


程式碼如下:

private void OnClick(object sender, RoutedEventArgs e)
{
     if (string.IsNullOrWhiteSpace(txtDir.Text))
     {
         MessageBox.Show(“請輸入目標存放文件的資料夾!!");
         return;
     }


    //如果目標資料夾不存在,就建立一個新的資料夾
     if (!Directory.Exists(txtDir.Text))
     {
         Directory.CreateDirectory(txtDir.Text);
     }


    int fileNum = 0;
     if (!int.TryParse(txtFileNum.Text, out fileNum))
     {
         MessageBox.Show(“請輸入檔案的數量!!"); return;
     }


    long fileSize = 0L;
     if (long.TryParse(txtSize.Text, out fileSize) == false)
     {
         MessageBox.Show(“請輸入預計每個檔案的大小!!");
         return;
     }


    //記錄要產生新的檔案名稱清單
     List<string> fileNames = new List<string>();


    for (int n = 0; n < fileNum; n++)
     {
         //檔案名稱
         string _filename = “file_" + (n + 1).ToString();


        //資料夾的絕對路徑
         string _dirpath = System.IO.Path.GetFullPath(txtDir.Text);


        //新的檔案的完整路徑
         string fullPath = System.IO.Path.Combine(_dirpath, _filename);


        //加入清單
         fileNames.Add(fullPath);
     }


    txtDisplay.Clear();


    //宣告一個Random 亂書產生器,目的待會用來產生每個檔案的隨機內容
     Random rand = new Random();


    //宣告一個 Action 委派任務,來產生每個檔案與檔案內容
     Action<string> act = (file) =>
         {
             FileInfo fileInfo = new FileInfo(file);


            //如果文件已經存在,就把它刪除
             if (fileInfo.Exists)
                 fileInfo.Delete();


            //開始進行隨機寫入內容
             byte[] buffer = new byte[fileSize];
             rand.NextBytes(buffer);


            using (FileStream fs = fileInfo.Create())
             {
                 BinaryWriter sw = new BinaryWriter(fs);
                 sw.Write(buffer);
                 sw.Close();
                 sw.Dispose();
             }


            //顯示執行結果
             string msg = string.Format(“檔案{0}已經建立完成!!\n", fileInfo.Name);
             this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => txtDisplay.AppendText(msg)));


        };


    //開始進行 Parallel 的循環平行任務作業
     Parallel.ForEach<string>(fileNames, act);


}



重點程式碼講解:

1.使用 Random rand = new Random();  ,來隨機產生每個檔案的內容。

2.宣告一個 Action 委派任務,來產生每個檔案與檔案內容。

Action<string> act = (file) =>
     {
         FileInfo fileInfo = new FileInfo(file);


        //如果文件已經存在,就把它刪除
         if (fileInfo.Exists)
             fileInfo.Delete();


        //開始進行隨機寫入內容
         byte[] buffer = new byte[fileSize];
         rand.NextBytes(buffer);


        using (FileStream fs = fileInfo.Create())
         {
             BinaryWriter sw = new BinaryWriter(fs);
             sw.Write(buffer);
             sw.Close();
             sw.Dispose();
         }


        //顯示執行結果
         string msg = string.Format(“檔案{0}已經建立完成!!\n", fileInfo.Name);
         this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => txtDisplay.AppendText(msg)));


    };

3.使用 Parallel.ForEach<string> 來開始進行 Parallel 的循環平行任務作業。

參考文章

C#多工作業與平行處理技術講解

1.透過 Thread 類別撰寫多執行緒多工作業。

2.透過 Delegate 委託支援的方法,撰寫非同步任務。

3-1.透過 Parallel 類別操控多任務平行作業(一)。

3-2. 透過 Parallel 類別操控多任務平行作業(二)。
4.使用 Task 自行控制非同步任務作業。
5.在非同步作業時,如何取消非同步任務。
6.多執行緒多任務存取相同變數,但卻各自隔離保留各自任務的值。
7.非同步存取變數的問題。
8.非同步資源鎖定解決方式。




網智數位-軟體開發(軟件開發)

針對各特殊產業都可以量身定做符合貴公司的需求,別人無法克服的就是我們的挑戰
業務合作、軟體委外開發
業務窗口:allen@netqna.com
聯繫電話:0920-883-870
公司電話:02-55991310
公司地址(業務營運處):台北市中山區錦州街 25 號 5 樓
skype: netqna
line:netqna
微信:netqna
黃先生 Allen