我正在学习事件,并发现使用Action代理也可以实现类似的功能。使用Action委托,它不是发布订阅模型,但它允许客户端传入类似于事件的方法引用,实际类可以在需要时调用它。
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);
}
}