C#子執行緒例項
阿新 • • 發佈:2018-12-04
做介面,前端告訴我,介面等待時間太長了,並且,介面返回值對其沒太大意義。於是,為了優化效率,決定採用一個子執行緒來單獨執行真正的寫資料的操作,而迅速地返回結果給前端。
核心程式碼如下:
Log.Loging.Info("Write Objects To Temp GeoGeoDatabase in a Child Thread ..."); //子執行緒方法定義 var aChildThread = new System.Threading.Thread((param) => { Log.Loging.Info("______Start ChildThread..."); var data = param as Tuple<ProjectInformation, List<object>, List<object>>; var aDataWriter = new ModelDataWriter() { TelecomOperator = data.Item1.TelecomOperator, WorkspacePath =data.Item1.GetProjectDataPath() }; Log.Loging.Info("Write Reels..."); var reels = aDataWriter.WriteObjects(data.Item2).Cast<object>().ToList(); Log.Loging.Info($"Reel Count = {reels.Count}"); Log.Loging.Info("Write Cores..."); var cores = aDataWriter.WriteObjects(data.Item3).Cast<object>().ToList(); Log.Loging.Info($"Core Count = {cores.Count}"); Log.Loging.Info("Finish ChildThread.______"); }); lock(aChildThread) { //啟動子執行緒 aChildThread.Start( new Tuple<ProjectInformation, List<object>, List<object>>( projectInfo, lsReel.Cast<object>().ToList(), lsCore.Cast<object>().ToList())); } Log.Loging.Info("Add Load Finished.<----------");
在這段程式碼中,我們將需要傳入的引數構造成一個元組Tuple,傳遞給子執行緒,然後啟動它。我們想要看到的結果應當是,輸出最後一句日誌資訊後,子執行緒裡還在執行寫資料的操作。我們看日誌,果然驗證這一點:
2018-09-03 11:26:31,783 [7] INFO : Write Objects To Temp GeoGeoDatabase in a Child Thread ... 2018-09-03 11:26:31,785 [7] INFO : Add Load Finished.<---------- 2018-09-03 11:26:31,797 [15] INFO : ______Start ChildThread... 2018-09-03 11:26:31,797 [15] INFO : Write Reels... 2018-09-03 11:26:34,951 [15] INFO : Reel Count = 48 2018-09-03 11:26:34,951 [15] INFO : Write Cores... 2018-09-03 11:27:13,955 [15] INFO : Core Count = 576 2018-09-03 11:27:13,955 [15] INFO : Finish ChildThread.______
介面測試時發現,原本順序執行,整個操作需要30~40秒才能完成,改用子執行緒後,返回結果只需要數毫秒。