zhengxu25689的专栏

对于c#接触差不多4个月,工作中用到是状态机和实时控制,下面线程实时监控的代码附上:

using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace ACON.AIAV3.Common{public class AutomateThread{public static Thread StartNew(ThreadStart start){Thread t = new Thread(start);t.Start();return t;}public static Result Monitor(int nTimeOutMS, ThreadStart start){Stopwatch sw = Stopwatch.StartNew();Thread t = AutomateThread.StartNew(() => { start(); });while (sw.ElapsedMilliseconds < nTimeOutMS){if (!t.IsAlive){return new Result(true, false);}else{Thread.Sleep(30);}}return new Result(false, true);}public static Result MonitorAll(int nTimeOutMS, params ThreadStart[] threadStart){Stopwatch sw = Stopwatch.StartNew();IList<Thread> threads = new List<Thread>();bool bFinish;foreach (var item in threadStart){var t = AutomateThread.StartNew(item);threads.Add(t);}while (sw.ElapsedMilliseconds <= nTimeOutMS){bFinish = true;foreach (var item in threads){if (item.IsAlive){Thread.Sleep(30);bFinish = false;}}if (bFinish){return new Result(true, false);}}return new Result(false, true);}public static void WaitAll(params Thread[] threads){Stopwatch sw = Stopwatch.StartNew();foreach(Thread t in threads){while(t != null && t.IsAlive){Thread.Sleep(30);}}}}}因为代码比较简单,就不作解释说明了。不明白处,可以留言。

,玩坏了可以选择重来,

zhengxu25689的专栏

相关文章:

你感兴趣的文章:

标签云: