110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
//线程状态枚举
enum ThreadStatus { Running,Stop};
class CopyMeterThreadPool
{
Stack<Thread> _pool;
//线程池初始化大小
private int _num;
public CopyMeterThreadPool(int capability)
{
_num = capability;
_pool = new Stack<Thread>(capability);
}
//压栈
public void Push(Thread thread)
{
if (thread == null)
throw new ArgumentNullException("线程池的线程未初始化!");
lock (_pool)
{
//重新包装要处理的Thread
SimpleThread st = new SimpleThread(thread);
//注册事件
st.OnThreadStop += new SimpleThread.ThreadStop(st_OnThreadStop);
_pool.Push(thread);
}
}
//事件委托的回收线程方法
void st_OnThreadStop(object sender, ThreadEventArgs e)
{
if (e.Status == ThreadStatus.Stop)
{
Thread t = (Thread)sender;
Push(t);
Console.WriteLine("成功放入线程池!");
}
}
//出栈
public Thread Pop()
{
lock (_pool)
{
return _pool.Pop();
}
}
public int Count
{
get { return _pool.Count; }
}
}
//封装线程的类
class SimpleThread
{
private Thread thread;
public Thread Thread
{
get { return thread; }
set { thread = value; }
}
//声明委托和事件
public delegate void ThreadStop(object sender, ThreadEventArgs e);
public event ThreadStop OnThreadStop;
public SimpleThread(Thread t)
{
thread = t;
}
//问题的关键在这里
public void SetStop()
{
if (thread.ThreadState == ThreadState.Running)
{
thread.Abort();
if (OnThreadStop != null)
{
if (thread.ThreadState == ThreadState.Aborted)
{
//thread.;
OnThreadStop(thread, new ThreadEventArgs(ThreadStatus.Stop));
}
}
}
}
}
//参数类
class ThreadEventArgs:EventArgs
{
private ThreadStatus status;
internal ThreadStatus Status
{
get { return status; }
}
public ThreadEventArgs(ThreadStatus status)
: base()
{
this.status = status;
}
}
}