SafeNet/.svn/pristine/c4/c41afbc3c66e134a43ad5f75256242afcb82c876.svn-base

58 lines
1.5 KiB
Plaintext
Raw Normal View History

2021-02-24 11:50:23 +00:00
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace SN_Server
{
public class InterthreadMessageQueue<T>
{
System.Collections.Generic.Queue<T> _queue = new
System.Collections.Generic.Queue<T>();
/// <summary>
/// Post a message to the queue.
/// </summary>
public void PostItem(T item)
{
lock (_queue)
{
_queue.Enqueue(item);
if (_queue.Count == 1)
Monitor.Pulse(_queue);
}
}
/// <summary>
/// Retrieve a message from the queue.
/// </summary>
/// <param name="maxWait">Number of milliseconds to block ifnothing is available. -1 means "block indefinitely"</param>
/// <returns>The next item in the queue, or default(T) if queue is empty</returns>
public T GetItem(int maxWait)
{
lock (_queue)
{
if (_queue.Count == 0)
{
if (maxWait == 0)
return default(T);
Monitor.Wait(_queue, maxWait);
if (_queue.Count == 0)
return default(T);
}
return _queue.Dequeue();
}
}
public int Count
{
get
{
lock (_queue)
{
return _queue.Count;
}
}
}
}
}