蛙蛙推荐:写了一个简单的延迟队列

写了一个简单的延迟队列,用于处理短时大量请求的情况,可以设置队列处理Handler,每次取队列的时间间隔,以及每次取多少队列项进行处理。

队列处理是同步执行。

  
  
public class LazyQueue < T >
{
public LazyQueue(Action < T > handler, int inteval, int onecount)
{
_handler
= handler;
_inteval
= inteval;
_onecount
= onecount;
_t
= new Thread(ThreadProc);
_t.Name
= " LazyQueue " ;
_t.IsBackground
= true ;
}
public void EnQueue(T item)
{
lock (_queue)
{
_queue.Enqueue(item);
}
}
public void Start()
{
_t.Start();
}

private void ThreadProc( object state)
{
while ( true )
{
try
{
List
< T > tempItems = new List < T > (_onecount);
lock (_queue)
{
for ( int i = _onecount - 1 ; i >= 0 ; i -- )
{
if (_queue.Count > 0 )
{
tempItems.Add(_queue.Dequeue());
}
}
}
tempItems.ForEach(_handler);

}
catch (Exception ex)
{
System.Diagnostics.Trace.TraceError(
" ThreadProc error:{0} " , ex);
}

Thread.Sleep(_inteval);
}
}

private Queue < T > _queue = new Queue < T > ();
private Action < T > _handler = null ;
private int _inteval = 0 ;
private int _onecount = 0 ;
private Thread _t = null ;
}

你可能感兴趣的:(队列)