Created
August 30, 2017 19:44
-
-
Save cezarypiatek/1368af68e9261e3a8775bc2631573af0 to your computer and use it in GitHub Desktop.
Producer with single thread consumer
This file contains 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
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