I am learning events and found that similar functionality can be achieved with Action delegates as well. With Action delegates, it is not publish subscribe model but it does allow the clients to pass in the method reference similar to events and actual class can call it when required.
class Program
{
static void Main(string[] args)
{
Subscriber s = new Subscriber();
NewSubscriber n = new NewSubscriber();
}
}
class TimeTick : EventArgs
{
public DateTime Current { get; set; }
public TimeTick()
{
}
}
/**Publisher suscriber model using events**/
delegate void MyDelegate(object o, TimeTick e);
class Publisher
{
public event MyDelegate MyEvent;
public Publisher()
{
}
public void Start()
{
while (1 == 1)
{
Thread.Sleep(5000);
if (MyEvent != null)
{
MyEvent(this, new TimeTick() { Current = DateTime.Now });
}
}
}
}
class Subscriber
{
public Subscriber()
{
Publisher p = new Publisher();
p.MyEvent += P_MyEvent;
p.Start();
}
private void P_MyEvent(object o, TimeTick e)
{
Console.WriteLine(e.Current);
}
}
/**Publisher suscriber model using Action delegates**/
class NewPublisher
{
public NewPublisher()
{
}
public void Start(Action<TimeTick> MyAction)
{
while (1 == 1)
{
Thread.Sleep(5000);
if (MyAction != null)
{
MyAction.Invoke(new TimeTick() { Current = DateTime.Now });
}
}
}
}
class NewSubscriber
{
public NewSubscriber()
{
NewPublisher p = new NewPublisher();
p.Start(new Action<TimeTick>(P_MyEvent));
}
public void P_MyEvent(TimeTick e)
{
Console.WriteLine(e.Current);
}
}