using System;
using System.Collections.Concurrent;
using System.Threading; namespace Base
{
public class WaitQueue<T> : IDisposable where T : class
{
/// <summary>
/// The deal action.
/// </summary>
public Action<T> DealAction { get; set; } /// <summary>
/// The inner queue.
/// </summary>
private readonly ConcurrentQueue<T> _innerQueue; /// <summary>
/// The deal thread.
/// </summary>
private readonly Thread dealThread; /// <summary>
/// The flag for end thread.
/// </summary>
private bool endThreadFlag = false; /// <summary>
/// The auto reset event.
/// </summary>
private readonly AutoResetEvent autoResetEvent = new AutoResetEvent(true); /// <summary>
/// Initializes a new instance of the WaitQueue`1 class.
/// </summary>
public WaitQueue()
{
this._innerQueue = new ConcurrentQueue<T>();
this.dealThread = new Thread(this.DealQueue);
this.dealThread.Start();
} /// <summary>
/// Disposes current instance, end the deal thread and inner queue.
/// </summary>
public void Dispose()
{
this.endThreadFlag = true;
this._innerQueue.Enqueue(null);
this.autoResetEvent.Set();
this.dealThread.Join();
this.autoResetEvent.Close();
} /// <summary>
/// Save entity to Queue.
/// </summary>
/// <param name="entity">The entity what will be deal.</param>
public void SaveLog(T entity)
{
this._innerQueue.Enqueue(entity);
this.autoResetEvent.Set();
} /// <summary>
/// Out Queue.
/// </summary>
/// <param name="entity">The init entity.</param>
/// <returns>The entity what will be deal.</returns>
private bool Dequeue(out T entity)
{
return this._innerQueue.TryDequeue(out entity);
} /// <summary>
/// Deal entity in Queue.
/// </summary>
private void DealQueue()
{
while (true)
{
T entity;
if (this.Dequeue(out entity))
{
if (this.endThreadFlag && entity == null)
{
return; // Exit the deal thread.
} try
{
if (this.DealAction != null)
{
this.DealAction(entity);
}
}
catch
{
}
}
else
{
this.autoResetEvent.WaitOne();
}
}
}
}
}

 

最新文章

  1. jQuery插件开发精品教程,让你的jQuery提升一个台阶
  2. json序列化及反序列化
  3. Json序列化与反序列化
  4. 外国javascript资源搜索
  5. hadoop研究:mapreduce研究前的准备工作
  6. Nginx部署ThinkPHP项目的办法
  7. js的传值,table中tr的遍历,js中动态创建数组
  8. 【BZOJ】【2631】Tree
  9. Framework 类库的事件编程
  10. SQL技巧之排名统计
  11. c#中使用easyUI的DataGrid组件
  12. hdu 4782 Beautiful Soupz
  13. JavaScript学习笔记(三)——留言板知操纵DOM节点
  14. POJ1032 Parliament(数论)
  15. JSON 数据操作
  16. JQuery --- 第一期 (初识jQuery, JQuery核心函数和工具方法)
  17. @EnableEurekaServer无法正常import原因是spring-cloud-dependencies版本太低
  18. C++整形转化成string类型---路径拼接在批处理程序中的应用
  19. INDEX--从数据存放的角度看索引
  20. 实现mysql按月统计的教程

热门文章

  1. 【Java】Observer Pattern
  2. win7桌面上的ie图标删不掉怎么办
  3. BZOJ1096 [ZJOI2007]仓库建设(斜率优化)
  4. cuda by example
  5. React Native 在用户网络故障时自动调取缓存
  6. T-Sql操作Xml数据(转)
  7. Codeforces Round #533 (Div. 2)题解
  8. HDU6315 Naive Operations(多校第二场1007)(线段树)
  9. angularJs增加行的操作
  10. [Groovy]Parse properties file in Groovy