[英]Why we are not invoking Events directly?
我見過許多開發人員想要調用一個Event
他們將它分配給名為handler
的局部變量並調用handler
而不是直接調用Event
。 為什么我們不直接調用事件?
private void OnSomethingChanged(EventArgs e)
{
if (SomethingEvent != null)
{
SomethingEvent(this, e);
}
}
你發布的代碼基本上不是線程安全的。 如果在不同的線程最終用戶取消訂閱后 if
檢查,但在調用之前 ,你會得到一個NullReferenceException
。
一種選擇是編寫擴展方法:
public static void NullSafeInvoke(this EventHandler handler,
object sender, EventArgs e)
{
if (handler != null)
{
handler(this, e);
}
}
然后你可以寫:
private void OnSomethingChanged(EventArgs e)
{
SomethingEvent.NullSafeInvoke(this, e);
}
你可能也想要EventHandler<T>
另一個重載。
如果未復制事件,則可能存在競爭條件(僅與多線程應用程序相關)。
如果一個線程在null
檢查之后立即取消訂閱該事件而不留下任何訂閱它,則會得到NullReferenceException
。
我也不明白為什么。 有一種簡單而安全的方法:
// when constructing of instance, to create empty subscription
public event EventHandler SomethingEvent = delegate { };
private void OnSomethingChanged(EventArgs e)
{
// and call it directly
SomethingEvent(this, e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.