Is my use of ConcurrentQueue here between 2 threads ok? I wanted to check I don’t need to “lock” anywhere explicitly. In particular look at the lines where I have in COMMENTS would I drop a packet here…
public class PacketCapturer
{
private static ConcurrentQueue<Packet> _packetQueue = new ConcurrentQueue<Packet>();
public PacketCapturer(IPHostEntry proxyDns, ref BackgroundWorker bw)
{
// start the background thread
var backgroundThread = new System.Threading.Thread(BackgroundThread);
backgroundThread.Start();
// Start Packet Capture with callback via PacketCapturerCallback
}
private void PacketCapturerCallback(Packet packet)
{
_packetQueue.Enqueue(packet);
}
private static void BackgroundThread()
{
while (!BackgroundThreadStop)
{
if (_packetQueue.Count == 0) Thread.Sleep(250);
else
{
ConcurrentQueue<Packet> ourQueue;
ourQueue = _packetQueue; // COULD I DROP A PACKET BETWEEN HERE
_packetQueue = new ConcurrentQueue<Packet>(); // AND HERE???
Console.WriteLine("BackgroundThread: ourQueue.Count is {0}", ourQueue.Count);
}
}
}
Edit: I think Mark/Gabe are right that you won’t lose any Packets. I’ll leave the rest in just for reference in case anyone else can weigh in on this.
Simply, yes. You could lose one or more Packets there. You might want to look into what methods ConcurrentQueue offers to get/remove a portion of it as that looks like what you want to do.
Why not TryDequeue until it returns false: