|
/// Author - anshu.dutta@gmail.com ///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Demo.Events.Observer
{
class Program
{
static void Main(string[] args)
{
Server s = new Server()
{
Clients= new List<IObserver>()
{
new Client(){ClientId=1},
new Client(){ClientId=2},
new Client(){ClientId=3}
}
};
while (true)
{
Thread.Sleep(new Random().Next(10) * 1000);
Console.WriteLine("Server Generating event {0}", DateTime.Now.ToString("hh:mm:ss"));
s.Notify();
}
}
}
public interface ISubject
{
void Add(IObserver Observer);
void Remove(IObserver observer);
void Notify();
}
public class Server : ISubject
{
public List<IObserver> Clients { get; set; }
public Server()
{
Clients = new List<IObserver>();
}
public void Add(IObserver Observer)
{
if (Clients != null)
Clients.Add(Observer);
}
public void Remove(IObserver observer)
{
if (Clients != null)
Clients.Remove(observer);
}
public void Notify()
{
//foreach (IObserver item in Clients)
//{
// item.Update();
//};
Parallel.ForEach<IObserver>(Clients, item =>
{
item.Update();
});
}
}
public interface IObserver
{
void Update();
}
public class Client : IObserver
{
public Client(){}
public int ClientId {get;set;}
public void Update()
{
Console.WriteLine("Event received from server by client {0} @ {1}", ClientId, DateTime.Now.ToString("hh:mm:ss"));
//Do work
ProcessEvent();
Console.WriteLine("Event processed by client {0} @ {1}", ClientId, DateTime.Now.ToString("hh:mm:ss"));
}
void ProcessEvent()
{
System.Threading.Thread.Sleep(2000);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I am a Senior Software Developer / Technical Consultant in a leading software company.