Last active
August 29, 2015 14:15
-
-
Save markbiek/5a811f695fa0a7189a20 to your computer and use it in GitHub Desktop.
ConcurrentQueue<T> example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.Linq; | |
using System.Text; | |
using System.Windows.Forms; | |
using System.Collections.Concurrent; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace QueueTest | |
{ | |
public partial class Form1 : Form | |
{ | |
private const int MonitorSleepLength = 10000; | |
private ConcurrentQueue<string> _queue = new ConcurrentQueue<string>(); | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
StartThreads(); | |
} | |
private string randomString(int len = 10) | |
{ | |
var rnd = new Random(); | |
var res = ""; | |
for (int i = 0; i < len; i++) | |
{ | |
int chr; | |
res += rnd.Next(0,1) == 0 ? (char) rnd.Next(65,90) : rnd.Next(97, 122); | |
} | |
return res; | |
} | |
private void StartThreads() | |
{ | |
Action populateQueue = () => | |
{ | |
while (true) | |
{ | |
//Add a new string to the queue, then sleep for a random period of time (1-50ms) | |
var rnd = new Random(); | |
var sleep = rnd.Next(1, 50); | |
var s = randomString(); | |
_queue.Enqueue(s); | |
Console.WriteLine("populateQueue: Added '" + s + "', sleeping for " + sleep.ToString()); | |
Thread.Sleep(sleep); | |
} | |
}; | |
Action processQueue = () => | |
{ | |
while (true) | |
{ | |
try | |
{ | |
//Read the next item out of the queue | |
//1 in 10 change of sleeping for 10 seconds before trying to dequeue again | |
var rnd = new Random(); | |
if (rnd.Next(1, 10) == 5) | |
{ | |
Console.WriteLine("processQueue: Sleeping for 10 seconds."); | |
Thread.Sleep(10 * 1000); | |
} | |
var s = ""; | |
_queue.TryDequeue(out s); | |
if (!string.IsNullOrEmpty(s)) | |
{ | |
Console.WriteLine("processQueue: Dequeued '" + s + "'"); | |
} | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine("Error in processQueue: " + e.Message); | |
} | |
} | |
}; | |
Action monitorQueue = () => | |
{ | |
//Periodically output the current state of the queue | |
while (true) | |
{ | |
Console.Write("monitorQueue: Queue has " + _queue.Count + " items."); | |
Thread.Sleep(MonitorSleepLength); | |
} | |
}; | |
Parallel.Invoke(populateQueue, processQueue, monitorQueue); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment