using System;
using System.Threading;
namespace Kingo.ThreadManager
{
public delegate void TaskParameterCallback(object obj);
public delegate void TaskCallback(TaskParameter parm);
public class CustomThread
{
ManualResetEvent _event = new ManualResetEvent(true);
ManualResetEvent _PoolEvent = null;
public bool IsActive = false;
public bool IsSuspend = false;
private TaskInfo Task;
//线程
private Thread t;
//委托,这里直接用 .NET 框架自带的,
//也可以根据需要自己定义一个
private TaskCallback w;
private TaskCallback c;
//传递给符合委托的回调方法的参数值,
//根据委托的定义而定
private TaskParameter o;
///
///执行回调方法的线程
///
public Thread CurrThread
{
get
{
return t;
}
}
public CustomThread(ManualResetEvent pPoolEvent)
{
_PoolEvent = pPoolEvent;
//线程还没有创建,创建一个新线程,并执行
t = new Thread(new ThreadStart(this.ThreadProc));
t.IsBackground = true;
t.SetApartmentState(ApartmentState.MTA);
}
///
///开启新线程或唤醒线程,去执行回调方法
///
///用回调方法实例化了的委托实例
///传递给回调方法的参数值
///true 表示线程为挂起状态,
///false 则表示线程还没创建
public void Start(TaskInfo pTask)
{
this.Task = pTask;
this.Task.IsWait = false;
//开启新线程或唤醒线程前,先设置
this.w = pTask.ExeFun;
this.o = pTask.Parameter;
this.c = pTask.ExeComplatFun;
//线程为挂起状态,唤醒线程继续执行
//if (IsSuspend)
//{
// //t.Resume();
// _event.Set();
// IsSuspend = false;
//}
//else
//{
t.Start();
//}
//IsActive = true;
Task.IsWait = false;
}
///
///线程执行的方法
///
private void ThreadProc()
{
//死循环,使线程唤醒后不是退出,而是继续通过委托执行回调方法
//while (true)
//{
try
{
//通过委托执行回调方法
//_event.WaitOne();
w(o);
if (c != null)
{
lock (c)
{
c?.Invoke(o);
//IsActive = false;
}
}
//_event.Reset();
//IsSuspend = true;
//IsActive = false;
}
catch (Exception ex)
{
throw;
}finally
{
IsActive = false;
Task.IsComplete = true;
_PoolEvent?.Set();
}
//t.Suspend();
//}
}
}
}