c#简单多线程实现
2019獨角獸企業重金招聘Python工程師標準>>>
去年底工作上遇到一個奇葩的需求,之前寫好的代碼實時讀取數據庫,并做出一些操作;結果領導認為這樣不好,要改成先去數據庫把該做的都做了,結果存在數據庫中,用的時候直接讀數據庫。試了一下,數據庫數據量太多,順序執行一遍需要4小時,不滿足時間上的要求,于是只能改一改,改成多線程的了。
?
因為之前的程序是完整的,所以直接摳出來,加了個多線程的殼,湊合完成了領導要求。因為這種多線程不涉及線程間通訊,比較簡單。下面給出源代碼
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Configuration; using System.IO;namespace MultiTask {class Program{static int m_timeout;static void Main(string[] args){// 從配置文件中讀入并發線程數和單個線程執行超時時間int concurrency = Convert.ToInt32(ConfigurationManager.AppSettings["concurrency"]);m_timeout = Convert.ToInt32(ConfigurationManager.AppSettings["timeout"]);// 創建線程任務排隊,concurrency即為同時運行的線程數量 LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(concurrency);List<Task> tasks = new List<Task>();// Create a TaskFactory and pass it our custom scheduler. TaskFactory factory = new TaskFactory(lcts);CancellationTokenSource cts = new CancellationTokenSource();var m_list = Init(); // 把數據從數據庫中取出來,放在m_list中準備處理// 創建任務,并添加到任務工廠運行 foreach (var ele in m_list){Info para = new Info(ele); // 將數據塞到合適的數據結構中Task t1 = factory.StartNew(() => { TestRun(para); }, cts.Token);tasks.Add(t1);}// 等待任務完成Task.WaitAll(tasks.ToArray());cts.Dispose();Console.WriteLine("Successful completion.");KillProcess();//Console.ReadKey();}// 把數據從數據庫中取出來static List<string> Init(){......}// 萬一有卡死的進程,殺掉static void KillProcess(){foreach (Process badprocess in Process.GetProcessesByName("TestRun")){badprocess.Kill();}}static void TestRun(Info info){Process p = new Process();p.StartInfo.FileName = "TestRun.exe"; // 運行以前的老程序p.StartInfo.Arguments = info.ID + " " + info.PRICE;p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;p.Start();bool flag = p.WaitForExit(m_timeout); // 等待運行結束或超時if (!flag) // 如果任務超時,打印log{FileStream fs = new FileStream("record.log", FileMode.Append);StreamWriter sw = new StreamWriter(fs);sw.WriteLine("[time out]: id = {0}, price = {1}", info.ID, info.PRICE);sw.Flush();sw.Close();fs.Close();}}}// 數據類public class Info{public int ID;public double PRICE;......} }上面的程序運行后,會同時運行concurrency個線程。當其中一個線程運行完或超時結束后,就再運行一個新的線程,直到所有任務全部完成。就實現領導提的簡單需求來說,已經足夠了。
轉載于:https://my.oschina.net/propagator/blog/1845885
總結
- 上一篇: 1.3(java学习笔记)构造方法及重载
- 下一篇: 2018-7-9