考慮下面的代碼:方法範圍變量的事件會發生什麼?
public class Bar {
Foo foo;
void Go() {
foo = new Foo();
foo.Send(...);
foo.Dispose();
foo = null;
}
}
public class Foo : IDisposable {
public void Send(byte[] bytes) {
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.SetBuffer(bytes, 0, bytes.Length);
args.UserToken = socket;
args.RemoteEndPoint = endPoint;
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnSendCompleted);
socket.SendAsync(args);
}
private void OnSendCompleted(object sender, SocketAsyncEventArgs e) {
Debug.WriteLine("great");
}
public void Dispose() {
//
}
}
所以Bar類運行初始化方法,該方法實例化Foo類和火災關閉Send方法,然後破壞了富實例。 Send方法同時實例化方法級別SocketAsyncEventArgs,設置Completed事件,然後觸發SendAsync方法。
假設SendAsync在Foo實例設置爲null之後完成,那麼事件處理程序會發生什麼?它還在燃燒嗎?如果我不希望它激發,我該如何正確地清理Foo類,知道方法級別變量會從事件中產生。
這樣做是否「安全」?它應該不會導致寫好的add-handler/remove-handler/raise-event代碼出現問題,但我不知道假定刪除事件處理程序不會被認爲是「安全」的,例如需要獲取可以在事件處理程序期間保持的鎖。有什麼明確說明這樣的假設被認爲是「安全的」,並且任何違反該假設的代碼都應該被認爲是「破碎的」? – supercat 2011-02-01 19:50:48