C#的EventHandler默认两个参数,第一个参数是事件的发送者(object类型),第二个参数是事件所包含的数据(EventArgs类型),并且返回值为void。如果需要传递其他类型的数据,可以使用泛型委托EventHandler<XX>。
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 定义_发布_订阅事件
{
internal class Program
{
static void Main(string[] args)
{
//调用事件(发布者)
PublishEvent publishEvent = new PublishEvent();
SubscribeEvent subscribeEvent = new SubscribeEvent(publishEvent); //订阅者1
SubscribeEvent subscribeEvent2 = new SubscribeEvent(publishEvent); //订阅者2
while (true)
{
ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();
if (consoleKeyInfo.KeyChar == 's') { break; }
if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "主"; };
if (consoleKeyInfo.KeyChar == 'p') //普通通知订阅者
{
publishEvent.Publish();
}
else if (consoleKeyInfo.KeyChar == 't') //线程通知订阅者
{
Thread thread = new Thread(() =>
{
publishEvent.Publish();
}
);
thread.Name = "子";
thread.Start();
}
}
}
}
//定义事件参数
public class MyPublishEventArgs : EventArgs
{
public string InfoString { get; set; }
}
//发布者
public class PublishEvent
{
public event EventHandler<MyPublishEventArgs> OnPublish;
public void Publish()
{
OnPublish?.Invoke(this, new MyPublishEventArgs() { InfoString = "hello " + Thread.CurrentThread.Name });//通知订阅者
}
}
//订阅者
public class SubscribeEvent
{
public SubscribeEvent(PublishEvent publishEvent)
{
publishEvent.OnPublish += Subscribe;
}
public void Subscribe(Object sender, MyPublishEventArgs args)
{
Console.WriteLine($"我接收到的消息是:{args.InfoString}");
}
}
}