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