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);
            }
        }
       
       

 

 

 


 

友情提示:

后续的几篇文章对其应用作了更新和封装,可以在专栏里查看。

如果感觉对你有帮助,请支持肯定下博主的努力!

 

 

 

 

 

 

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值