C# 实时监控线程类

    本人自己所在的项目是仪器的时序控制层代码开发。

下面简单说下需求的来源:

1. 需要把控制分多个任务,每个任务又包括了多个子任务。

2. 每个子任务需要按控制时序线固定起始时间开始执行,指定时间长内完成子任务。

所以才考虑到自己封装一个可以实时监控线程类来完成多个子任务的串行或并行执行,并在指定时间内返回是否执行成功或超时。

下面是实现的代码,主要是可以用此类更为方便操作线程。(这里要强调一点:如果实时性要求高,尽量使用Thread,不要用Task


using System.Threading;

namespace XXX.Common
{
    public class AutomateThread
    {
        private const int SLEEP_TICK = 1;
        private const int SLEEP_WAIT_TICK = 100;
        
        \\执行单个任务,返回线程
        public static Thread StartNew(ThreadStart start, ThreadPriority priority = ThreadPriority.Normal)
        {
            Thread t = new Thread(start);

            t.IsBackground = true;
            t.Priority = priority;
            t.Start();

            return t;
        }

        \\同时执行多个任务,并等待执行结束
        public static void TasksExecuteAsyn(params ThreadStart[] starts)
        {
            Thread[] threads = new Thread[starts.Length];

            for (int i = 0; i < starts.Length; i++)
            {
                threads[i] = StartNew(starts[i]);
            }

            WaitAll(threads);
        }
        \\单个任务,在给定执行时间内返回执行是否超时
        public static bool Monitor(int period, ThreadStart start)
        {
            Tickwatch sw = Tickwatch.StartNew();
            Thread t = AutomateThread.StartNew(start);

            while (sw.ElapsedMilliseconds < period)
            {
                if (!t.IsAlive)
                {
                    return false;
                }

                AutomateThread.Sleep(SLEEP_TICK);
            }

            return true;
        }
         
        \\等待所有线程执行结束
        public static void  WaitAll(params Thread[] threads)
        {
            foreach (Thread t in threads)
            {
                while (t != null && t.IsAlive)
                {
                    AutomateThread.Sleep(SLEEP_TICK);
                }
            }
        }
        
        \\主动释放CPU短等待时间
        public static void Sleep(int milliseconds)
        {
            Tickwatch watch = Tickwatch.StartNew();

            while(watch.ElapsedMilliseconds <= milliseconds)
            {
                Thread.Sleep(SLEEP_TICK);
            }
        }
       
       


 
 




    

猜你喜欢

转载自blog.csdn.net/zhengxu25689/article/details/79359000