订阅事件/委托时通知的任何方式
本文关键字:任何方 何方 通知 事件 | 更新日期: 2023-09-27 18:22:33
当有东西订阅了我类中的事件时,有没有任何方法可以得到通知,或者我需要用方法包装订阅/取消订阅,例如:
public class MyClass : ISomeInterface
{
public event SomeEventHandler SomeEvent; //How do I know when something subscribes?
private void OnSomeEventSubscription(SomeEventHandler handler)
{
//do some work
}
private void OnSomeEventUnsubscription(SomeEventHandler handler)
{
//do some work
}
}
而不是
public class MyClass : ISomeInterface
{
private SomeEventHandler _someEvent;
public void SubscribeToSomeEvent(SomeEventHandler handler)
{
_someEvent += handler;
//do some work
}
public void UnsubscribeFromSomeEvent(SomeEventHandler handler)
{
_someEvent -= handler;
//do some work
}
}
我之所以这么问,是因为事件已经直接在ISomeInterface
上公开,但这个特定的实现需要知道什么时候订阅/取消订阅。
您可以为您的事件编写自定义访问者:
private SomeEventHandler _someEvent;
public event SomeEventHandler SomeEvent
{
add
{
_someEvent += value;
Console.WriteLine("Someone subscribed to SomeEvent");
}
remove
{
_someEvent -= value;
Console.WriteLine("Someone unsubscribed from SomeEvent");
}
}
Thomas已经回答了这个问题,但我想补充一点,您可能需要锁定添加-删除部分中的任何关键部分,因为事件订阅从来都不是线程安全的,也就是说,您不知道谁或何时会连接到您。例如:
private readonly object _objectLock = new object();
private SomeEventHandler _someEvent;
public event SomeEventHandler SomeEvent
{
add
{
lock(_objectLock)
{
_someEvent += value;
// do critical processing here, e.g. increment count, etc could also use Interlocked class.
} // End if
} // End of class
remove
{
lock(_objectLock)
{
_someEvent -= value;
// do critical processing here, e.g. increment count, etc could also use Interlocked class.
} // End if
} // End if
} // End of event