SafeNet/SN_Server/QueueDefine.cs
2021-02-24 13:50:23 +02:00

58 lines
1.5 KiB
C#

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;
}
}
}
}
}