C# Pub/Sub example

public class PubSub
{
readonly Queue<string> queue = new Queue<string>();

object locker = new object();

public string Subscribe()
{
string text;
lock (locker)
{
while(queue.Count== 0)
{
Monitor.Wait(locker);
}
text = queue.Dequeue();
}
return text;
}

public void Publish(string request)
{
lock (locker)
{
queue.Enqueue(request);
Monitor.PulseAll(locker);
}
}
}

class Program
{
Random r = new Random();

public Program()
{
PubSub pubSub = new PubSub();

Thread t1 = new Thread(delegate() { Publish(pubSub); });
Thread t2 = new Thread(delegate() { Subscribe(pubSub); });

t1.Start();
t2.Start();

t1.Join();
t2.Join();

Console.WriteLine("Completed.");

Console.ReadLine();
}

void Publish(PubSub pubSub)
{
for (int i = 1; i <= 10; i++)
{
Thread.Sleep(r.Next(10, 100));
pubSub.Publish(string.Format("Publishing {0}",i));
}
pubSub.Publish(null);
}

void Subscribe(PubSub pubSub)
{
while(true)
{
string text = pubSub.Subscribe();
if(text==null) return;
Console.WriteLine(text);
}
}

static void Main(string[] args)
{
new Program();
}
}

Comments

Popular posts from this blog

Parse XML to dynamic object in C#

C# Updating GUI from different thread