1. 程式人生 > >貼 一個Thread 程式碼(自用)

貼 一個Thread 程式碼(自用)

貼 一個Thread 執行程式碼

請將執行函式放在MainMethod()中!

詳細:
1、帶有 Init()函式;
2、帶有Abort()函式;另設計了AbortAsync()任務。
3、加入Watchdog!

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace DemoModbus
{
    class ModbusRun
    {
        public static Task<bool
> TaskWatchdog; public static void Init() { threadModbusRun = new Thread(new ThreadStart(() => IsEnd = FucAFlow())); threadModbusRun.Start(); TaskWatchdog = new Task<bool>(FucWatchdog, TaskCreationOptions.LongRunning); TaskWatchdog.Start(); } ///
<summary>
/// 函式:執行緒結束功能。執行時間不大於2s。 /// </summary> public static void Abort() { // bool res = false; LoopEnable = false; Stopwatch sw_AlarmDealy = new Stopwatch(); sw_AlarmDealy.Start(); while (!IsEnd && sw_AlarmDealy.ElapsedMilliseconds < 2000
) ; sw_AlarmDealy.Stop(); if (!IsEnd) { threadModbusRun.Abort(); } return; } /// <summary> /// 任務:執行緒結束功能。執行時間不大於2s,根據task.IsCompleted判斷。 /// </summary> public static Task AbortAsync() { return Task.Run(() => { Abort(); }); } private static Thread threadModbusRun; private static bool IsEnd = false; /// <summary> /// 阻塞器 /// </summary> public static bool Loopblock = false; /// <summary> /// 迴圈Enable /// </summary> public static bool LoopEnable = true; /// <summary> /// Note:一個週期 不要超出1s /// </summary> /// <returns></returns> private static bool FucAFlow() { while (LoopEnable) { if (Loopblock) { Thread.Sleep(1000); continue; } Thread.Sleep(10); try { MainMethod(); } catch (Exception ex) { Console.WriteLine(ex.Message); // LogTool.WriteLog(ex.Message, LogTool.LogType.logError); } } return true; } /// <summary> /// 看門狗 /// </summary> public static bool Watchdog = false; public static long MillisecondsInPrePeriod = 0; private static Stopwatch sw_Watchdog = new Stopwatch(); private static AutoResetEvent autoResetEvent_Watchdog = new AutoResetEvent(false); private static void MainMethod() { autoResetEvent_Watchdog.Set(); Thread.Sleep(1000); //throw new NotImplementedException(); } private static bool FucWatchdog() { sw_Watchdog.Start(); while (LoopEnable) { Thread.Sleep(10); if (autoResetEvent_Watchdog.WaitOne(200)) { Watchdog = true; //喂狗 MillisecondsInPrePeriod = sw_Watchdog.ElapsedMilliseconds; sw_Watchdog.Restart(); } if (sw_Watchdog.ElapsedMilliseconds > 2000) { Watchdog = false; //餓死 狗 } } sw_Watchdog.Stop(); return true; } } }