在C#中,为了避免事件的滥用,可以采取以下几种策略:
WeakReference
和EventHandler<T>
来实现弱事件模式。例如:public class EventPublisher
{
private readonly WeakEvent<EventHandler<EventArgs>> _event = new WeakEvent<EventHandler<EventArgs>>();
public event EventHandler<EventArgs> MyEvent
{
add => _event.Register(value);
remove => _event.Unregister(value);
}
protected virtual void OnMyEvent(EventArgs e)
{
_event?.Invoke(this, e);
}
}
public class EventSubscriber
{
public void Subscribe(EventPublisher publisher)
{
publisher.MyEvent += OnMyEvent;
}
public void Unsubscribe(EventPublisher publisher)
{
publisher.MyEvent -= OnMyEvent;
}
private void OnMyEvent(object sender, EventArgs e)
{
// 处理事件
}
}
public class CustomEventArgs : EventArgs
{
public string Message { get; set; }
public CustomEventArgs(string message)
{
Message = message;
}
}
public class EventPublisher
{
public event EventHandler<CustomEventArgs> MyEvent;
protected virtual void OnMyEvent(CustomEventArgs e)
{
MyEvent?.Invoke(this, e);
}
}
public class EventSubscriber
{
public void Subscribe(EventPublisher publisher)
{
publisher.MyEvent += OnMyEvent;
}
public void Unsubscribe(EventPublisher publisher)
{
publisher.MyEvent -= OnMyEvent;
}
private void OnMyEvent(object sender, CustomEventArgs e)
{
// 根据需要处理事件
}
}
SemaphoreSlim
来限制订阅者的数量:public class EventPublisher
{
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(10);
public event EventHandler<EventArgs> MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
_semaphore.Wait();
try
{
MyEvent?.Invoke(this, e);
}
finally
{
_semaphore.Release();
}
}
}
On[EventName]Changed
或[EventName]Occurred
等命名方式。通过以上策略,可以在C#中有效地避免事件的滥用。