namespace HuanMeng.DotNetCore.Processors
{
///
/// 包含处理线程的处理器基类
///
public abstract class ThreadProcessor : BaseProcessor
{
protected Thread? _thread;
protected bool _isRunning;
protected string? _threadName;
///
/// 构造函数
///
public ThreadProcessor() { }
///
/// 构造函数
///
/// 线程名称
public ThreadProcessor(string threadName)
{
_threadName = threadName;
}
///
/// 执行处理
///
/// 如果处理器已经在运行,抛出异常
public override void Run()
{
if (_isRunning)
{
throw new InvalidOperationException("重复执行线程");
}
_isRunning = true;
_thread = new Thread(Proc_Do)
{
Name = _threadName
};
_thread.Start();
}
///
/// 线程处理函数,需要在子类中实现
///
protected abstract void Proc_Do();
///
/// 停止处理线程
///
public override void Stop()
{
if (!_isRunning)
{
return;
}
_isRunning = false;
if (_thread != null && _thread.IsAlive)
{
_thread.Join(WaitTimeMax_StopProc); // 等待线程结束
_thread = null;
}
}
///
/// 释放资源
///
public override void Dispose()
{
Stop();
base.Dispose();
}
}
}