MailManager.cs 1.0 KB

1234567891011121314151617181920212223242526272829
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. namespace EventDemo
  6. {
  7. public class MailManager
  8. {
  9. // 定义事件成员
  10. // public delegate void EventHandler<[NullableAttribute(2)] TEventArgs>([NullableAttribute(2)] object? sender, TEventArgs e);
  11. public event EventHandler<NewMailEventArgs> NewMail;
  12. // 定义负责引发事件的方法来通知已登记的对象
  13. protected virtual void OnNewMail(NewMailEventArgs e)
  14. {
  15. // 将字段复制到一个临时变量,避免多线程情况中这个成员被移除
  16. EventHandler<NewMailEventArgs> temp = Volatile.Read(ref NewMail);
  17. if (temp != null) temp(this, e);
  18. }
  19. // 接受附加信息并调用引发事件的方法来通知所有登记的对象
  20. public void SimulateNewMail(string from, string to, string content)
  21. {
  22. NewMailEventArgs e = new NewMailEventArgs(from, to, content);
  23. OnNewMail(e);
  24. }
  25. }
  26. }