Skip to content

Instantly share code, notes, and snippets.

@phizaz
Created June 21, 2017 10:59
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/1d2dc0798696341277ac803787eeee1f to your computer and use it in GitHub Desktop.
Save phizaz/1d2dc0798696341277ac803787eeee1f to your computer and use it in GitHub Desktop.
C# Producer-Consumer Pattern with Timeout and Callback
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
{
delegate void Callback(int c);
class Job
{
public int a;
public int b;
public Callback callback;
}
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
// simulate the plus function
var c = job.a + job.b;
// call the callback
job.callback(c);
}
}
}
public void addJob(Job job)
{
// add to queue
this.blockingQueue.Add(job);
}
}
class Program
{
static void Main(string[] args)
{
var consumer = new Consumer();
consumer.addJob(new Job() {
a = 10,
b = 20,
callback = delegate(int c)
{
Console.WriteLine("c: " + c);
}
});
consumer.addJob(new Job()
{
a = 11,
b = 21,
callback = delegate (int c)
{
Console.WriteLine("c: " + c);
}
});
Thread.Sleep(3000);
consumer.addJob(new Job()
{
a = 12,
b = 22,
callback = delegate (int c)
{
Console.WriteLine("c: " + c);
}
});
Thread.Sleep(3000);
consumer.abort();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment