the wait queue
2024-08-29 07:47:04
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();
}
}
}
}
}
最新文章
- jQuery插件开发精品教程,让你的jQuery提升一个台阶
- json序列化及反序列化
- Json序列化与反序列化
- 外国javascript资源搜索
- hadoop研究:mapreduce研究前的准备工作
- Nginx部署ThinkPHP项目的办法
- js的传值,table中tr的遍历,js中动态创建数组
- 【BZOJ】【2631】Tree
- Framework 类库的事件编程
- SQL技巧之排名统计
- c#中使用easyUI的DataGrid组件
- hdu 4782 Beautiful Soupz
- JavaScript学习笔记(三)——留言板知操纵DOM节点
- POJ1032 Parliament(数论)
- JSON 数据操作
- JQuery --- 第一期 (初识jQuery, JQuery核心函数和工具方法)
- @EnableEurekaServer无法正常import原因是spring-cloud-dependencies版本太低
- C++整形转化成string类型---路径拼接在批处理程序中的应用
- INDEX--从数据存放的角度看索引
- 实现mysql按月统计的教程
热门文章
- 【Java】Observer Pattern
- win7桌面上的ie图标删不掉怎么办
- BZOJ1096 [ZJOI2007]仓库建设(斜率优化)
- cuda by example
- React Native 在用户网络故障时自动调取缓存
- T-Sql操作Xml数据(转)
- Codeforces Round #533 (Div. 2)题解
- HDU6315 Naive Operations(多校第二场1007)(线段树)
- angularJs增加行的操作
- [Groovy]Parse properties file in Groovy