Consider the following code:
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() {
//
}
}
So class Bar runs the Init method which instantiates the Foo class and fires off the Send method, then destroys the Foo instance. The Send method meanwhile instantiates a method level SocketAsyncEventArgs, sets up a Completed event and then fires off the SendAsync method.
Assuming that the SendAsync completes after the Foo instance has been set to null, what happens to the event handler? Does it still fire? If I don't want it to fire, how do I properly clean up the Foo class, knowing that a method level variable spawned off an event.