2016-09-14 79 views
1

在下面的代碼中還沒有添加註銷事件處理程序的用途是什麼?這樣使用EventHandler有什麼意義?

public class foo 
{ 
    private event EventHandler<boo> booCompleted; 

    public RegisterBooCompletedHandler(EventHandler<boo> newBooCompletedEventHandler, bool forceUnregisterOtherEventHandlers) 
    { 
     if (forceUnregisterOtherEventHandlers) 
      booCompleted = null 

     booCompleted -= newBooCompletedEventHandler;  // <- why do we unregister not added yet event handler? 
     booCompleted += newBooCompletedEventHandler; 
    } 
} 
+0

這可能是要確保有一個與該事件相關聯,沒有預先存在的事件處理程序添加一個之前,或者在這種情況下,確保booCompleted沒有現有的鏈接newBooCompletedEventHandler。 (如果RegisterBooCompletedHandler以某種方式被錯誤地調用兩次,會發生) –

回答

4

這意味着,如果你調用RegisterBooCompletedHandler(handler)用相同的處理多次,你還是實際上只訂閱事件一次該處理程序。

我的猜測是,實際上你已經看到了這個由於工作的人在那裏圓真的,他們訂閱的事件在錯誤的地方,所以訂閱多次出現問題......但我敢肯定有是一些情況下,很難知道你是否已經訂閱或只是使它幾乎沒有操作再次訂閱很方便。

我說這是一個「(幾乎)沒有操作」,因爲它改變了順序。試想一下:

// After this call, invocation list is A 
RegisterBooCompletedHandler(A, false); 
// After this call, invocation list is A, B 
RegisterBooCompletedHandler(B, false); 
// After this call, invocation list is A, B, C 
RegisterBooCompletedHandler(C, false); 
// After this call, invocation list is A, C, B 
RegisterBooCompletedHandler(B, false);