Last active
December 28, 2015 00:48
-
-
Save omerfarukz/7415554 to your computer and use it in GitHub Desktop.
Simple pub sub pattern demo
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.Generic; | |
using System.Threading; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
MessageManager mm = new MessageManager(); | |
mm.OnMessageReceived += mm_OnMessageReceived; | |
mm.Begin(); | |
Console.WriteLine("Client started"); | |
Console.ReadKey(); | |
} | |
static void mm_OnMessageReceived(Message msg) | |
{ | |
Console.WriteLine("You have new message from publisher. Id:" + msg.Id + ", Text:" + msg.Text); | |
} | |
} | |
public class MessageManager | |
{ | |
public delegate void OnMessageReceivedDelegate(Message Message); | |
public event OnMessageReceivedDelegate OnMessageReceived; | |
private DemoService _service; | |
private IEnumerable<Message> _messages; | |
public MessageManager() | |
{ | |
} | |
public void Begin() | |
{ | |
while (true) | |
{ | |
HandleNewMessage(); | |
} | |
} | |
private void HandleNewMessage() | |
{ | |
Console.WriteLine("New connection is opening"); | |
_service = new DemoService(); | |
_messages = _service.GetAll(); | |
var enumerator = _messages.GetEnumerator(); | |
while (enumerator.MoveNext()) | |
{ | |
if (OnMessageReceived != null) | |
{ | |
OnMessageReceived(enumerator.Current); | |
} | |
} | |
Console.WriteLine("Connection is closed"); | |
} | |
} | |
public class Message | |
{ | |
public int Id { get; set; } | |
public string Text { get; set; } | |
} | |
public class DemoService | |
{ | |
public IEnumerable<Message> GetAll() | |
{ | |
for (int i = 0; i < 20; i++) | |
{ | |
Thread.Sleep(new Random().Next(10, 300)); | |
yield return new Message() { Id = i, Text = "Message " + i + " is published" }; | |
} | |
yield break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment