![](/img/trans.png)
[英]How to make dynamically created object's event handler reference a DGV object in another class?
[英]Why make another reference to the event handler in this example?
這是示例代碼: http : //msdn.microsoft.com/zh-cn/library/system.eventhandler.aspx
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
我們是否只能直接檢查ThresholdReached
是否為null
?
是的,您可以直接檢查null。
這種編碼風格有助於解決多線程問題。 如果檢查ThresholdReached
是否為null,然后另一個線程將其設置為null,然后嘗試運行處理程序,它將失敗。 不太可能,但是如果您正在運行多個線程,則可能。
因此,在此示例中,您首先獲取ThresholdReached
,以便可以檢查null
並調用它,而不必擔心其他線程在兩次調用之間會混淆該值。 如果您不關心多線程,那么請務必直接檢查null。
在存在多線程問題的各種情況下,您都會發現這種防御性編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.