C# 如何讓 多執行緒中每個執行緒間隔毫秒執行同一個方法
阿新 • • 發佈:2019-01-30
class Program { static int dur = 200; static string tm = ""; static void Main(string[] args) { for (int i = 0; i < 10; i++) { var td = new Thread(new ThreadStart( () => { lock (tm) { if (tm == "") { Thread.Sleep(dur); } else { var t=DateTime.Now.Subtract(DateTime.Parse(tm)); Thread.Sleep(dur - (int)t.TotalSeconds); } }; DoSomeThing(); } )); td.Start(); } Console.Read(); } private static void DoSomeThing() { tm = DateTime.Now.ToShortTimeString(); string info = string.Format("執行緒ID:{0},執行時間:{1}" , Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:ffff")); Console.WriteLine(info); Thread.Sleep(5000); } }