线程阻塞+递归实现
这里使用ConcurrentQueue来作为存放消息的容器,MessageQueue实例化时,开启线程来对消息进行处理,当容器为空时,可以使用EventWaitHandle堵塞线程
EventWaitHandle使用:
Set():解除线程堵塞。
WaitOne():阻止当前线程继续运行。
class MessageQueue<T>
{
private ConcurrentQueue<T> queue=null;//用来存放数据的容器
private bool isRunning = false;//线程是否启动
private bool isWait = false;//信号
private Thread thread = null;
private Action action = null;
private EventWaitHandle eventWaitHandle = new AutoResetEvent(false);
private void Go() {
if (!isRunning)
{
isRunning = true;
action = new Action(DoRun);
RunAction();
}
}
private void RunAction() {
action.BeginInvoke(RunEnd, action);
}
private void RunEnd(IAsyncResult ar)
{
action.EndInvoke(ar);
if (queue.IsEmpty) {
isWait = true;
eventWaitHandle.WaitOne();
isWait = false;
}
RunAction();
}
private void DoRun() {
try {
T str;
bool b = queue.TryDequeue(out str);
if (b)
{
//......
//这里对容器内的数据进行处理
//......
}
} catch (Exception e) {
Console.WriteLine("[ Exception :"+e+"]" );
} finally {
}
}
/// <summary>
/// 入队
/// </summary>
/// <param name="node"></param>
public void AppendMessage(T node) {
queue.Enqueue(node);
if (isWait)
{
eventWaitHandle.Set();
}
}
//初始化
public void Start() {
if (thread==null) {
queue = new ConcurrentQueue<T>();
thread = new Thread(Go);
thread.Start();
}
}
}