SafeDispatch/TCPServerService/InterthreadMessageQueue.cs

132 lines
2.7 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class InterthreadMessageQueue<T>
{
private DateTime lastReadTime = DateTime.Now;
public DateTime LastReadTime
{
get { return lastReadTime; }
private set { lastReadTime = value; }
}
Queue<T> _queue = new 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>
/// Post a message to the queue.
/// </summary>
public void PostItems(List<T> items)
{
lock (_queue)
{
foreach (T item in items)
_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)
{
LastReadTime = DateTime.Now;
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 T Peek(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.Peek();
}
}
public void Remove(T item)
{
lock (_queue)
{
if (_queue.Count != 0)
{
T itemPeek = _queue.Peek();
if (itemPeek.Equals(item))
{
_queue.Dequeue();
}
}
}
}
public void Clear()
{
lock (_queue)
{
if (_queue.Count != 0)
{
_queue.Clear();
}
}
}
public List<T> ToList()
{
lock (_queue)
{
return _queue.ToList();
}
}
public int Count
{
get
{
lock (_queue)
{
return _queue.Count;
}
}
}
}