贴 一个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;
}
}
}