Skip to content

Instantly share code, notes, and snippets.

@cezarypiatek
Created August 30, 2017 19:44
Show Gist options
  • Save cezarypiatek/1368af68e9261e3a8775bc2631573af0 to your computer and use it in GitHub Desktop.
Save cezarypiatek/1368af68e9261e3a8775bc2631573af0 to your computer and use it in GitHub Desktop.
Producer with single thread consumer
public class ProducerConsumer<T>
{
readonly BlockingCollection<T> dataToProcess = new BlockingCollection<T>();
private readonly Thread workerThread;
public ProducerConsumer(Action<T> action)
{
workerThread = new Thread(() =>
{
foreach (var data in dataToProcess.GetConsumingEnumerable())
{
action(data);
}
Console.WriteLine("Finish");
});
}
public void Post(T data)
{
if (workerThread.ThreadState == ThreadState.Unstarted)
{
workerThread.Start();
}
dataToProcess.Add(data);
}
~ProducerConsumer()
{
dataToProcess.CompleteAdding();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment