NOTE:
i did a complete rework of my question. you can see the original question via the change-history.
i\'m in the need of a "mighty&qu
I wrote an easy example that works fine for me and should be suitable for your scenarios. If the consumer is running is depending of how the running variable is set, but you easily modify it to a more complex condition like "if no mail exists but someone said I should wait for more".
public class MailSystem
{
private readonly Queue mailQueue = new Queue();
private bool running;
private Thread consumerThread;
public static void Main(string[] args)
{
MailSystem mailSystem = new MailSystem();
mailSystem.StartSystem();
}
public void StartSystem()
{
// init consumer
running = true;
consumerThread = new Thread(ProcessMails);
consumerThread.Start();
// add some mails
mailQueue.Enqueue(new Mail("Mail 1"));
mailQueue.Enqueue(new Mail("Mail 2"));
mailQueue.Enqueue(new Mail("Mail 3"));
mailQueue.Enqueue(new Mail("Mail 4"));
Console.WriteLine("producer finished, hit enter to stop consumer");
// wait for user interaction
Console.ReadLine();
// exit the consumer
running = false;
Console.WriteLine("exited");
}
private void ProcessMails()
{
while (running)
{
if (mailQueue.Count > 0)
{
Mail mail = mailQueue.Dequeue();
Console.WriteLine(mail.Text);
Thread.Sleep(2000);
}
}
}
}
internal class Mail
{
public string Text { get; set; }
public Mail(string text)
{
Text = text;
}
}