在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#中有效地避免事件的濫用。