views:

90

answers:

2

Can anyone tell me if I'm likely to run into unintended behavior if I use anonymous methods with Async I/O?

As an example:

Action<Socket> acceptedHandler = DoAccept
SocketAsyncEventArgs e = new SocketAsyncEventArgs();

e.Completed += ((sender, ea) => acceptedHandler(ea.AcceptSocket));

// Server is a Socket
if (!Server.AcceptAsync(e))
    acceptedHandler(e);

The same applies to BeginXXX/EndXXX async I/O.

+1  A: 

There is nothing to worry about when using anonymous methods. Your example is actually a good example of when to use them. Indecently remember to properly use the SocketAsyncEventArgs class. I am hoping your example is extremely contrived.

ChaosPandion
What do you mean "decently remember to properly use the Socket AsyncEventArgs class"? It's not contrived, but it is simplified.
Mystere Man
You really need to declare SocketAsyncEventArgs as a member of an outer class so you can properly dispose of it.
ChaosPandion
I reuse the SocketAsyncEventArgs, so i don't want to dispose of it.
Mystere Man
I know but you still need to dispose of it eventually if you want to shutdown your server gracefully.
ChaosPandion
+1  A: 

From the code snippet you pasted it doesn't seem like there would be any issue. The only time to worry about anonymous methods is when you are capturing variables.

TskTsk
Isn't that capturing the acceptedHandler delegate?
Mystere Man
Indeed... I was thinking more about when you reference variables that have mutable objects like lists and such. If you later change the value of acceptedHandler and the even is fired you'll call into whatever it is referring to at that point, not the original DoAccept.
TskTsk
Ok, so in this example, isn't the SocketAsyncEventArgs mutable? Especially since it can be reused and you can have multiple Accepts pending?
Mystere Man
Definitely... if you change what acceptedHandler is pointing to and then the event is fired, you will get different behavior. It all depends on whether you'll be changing acceptedHandler within that scope. It's hard to tell what will happen with just the few lines of code there. If the code you have above is wrapped inside curly braces, then you don't have to worry about it.
TskTsk