Created
June 21, 2017 09:23
-
-
Save phizaz/bbda462ec52b2a561d488ae8e1cfe6ae to your computer and use it in GitHub Desktop.
C# Producer-Consumer Pattern with Timeout
This file contains hidden or 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
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