Skip to content

Instantly share code, notes, and snippets.

@phizaz
Created June 21, 2017 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phizaz/bbda462ec52b2a561d488ae8e1cfe6ae to your computer and use it in GitHub Desktop.
Save phizaz/bbda462ec52b2a561d488ae8e1cfe6ae to your computer and use it in GitHub Desktop.
C# Producer-Consumer Pattern with Timeout
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ProducerConsumer
{
class Job
{
public int a;
public int b;
}
class Consumer
{
ConcurrentQueue<Job> queue;
BlockingCollection<Job> blockingQueue;
Thread thread;
~Consumer()
{
this.abort();
}
public Consumer()
{
this.queue = new ConcurrentQueue<Job>();
this.blockingQueue = new BlockingCollection<Job>(queue);
this.thread = new Thread(this.work);
this.thread.Start();
}
public void abort()
{
if (this.thread != null)
{
this.thread.Abort();
this.thread.Join();
this.thread = null;
}
}
private void work()
{
var timeout = 1000;
while(true)
{
Job job;
var succeed = this.blockingQueue.TryTake(out job, timeout);
if (!succeed)
{
// timeout
Console.WriteLine("timeout");
}
else
{
// okay
Console.WriteLine("job: a: " + job.a + " b: " + job.b);
}
}
}
public void addJob(Job job)
{
this.blockingQueue.Add(job);
}
}
class Program
{
static void Main(string[] args)
{
var consumer = new Consumer();
consumer.addJob(new Job() { a = 10, b = 20 });
consumer.addJob(new Job() { a = 11, b = 21 });
Thread.Sleep(3000);
consumer.addJob(new Job() { a = 12, b = 22 });
Thread.Sleep(3000);
consumer.abort();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment