0

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.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291

2 Answers2

1

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
  • 77,506
  • 18
  • 119
  • 157
1

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.

jvilalta
  • 6,679
  • 1
  • 28
  • 36
  • 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. – jvilalta Dec 23 '09 at 16:05
  • Ok, so in this example, isn't the SocketAsyncEventArgs mutable? Especially since it can be reused and you can have multiple Accepts pending? – Erik Funkenbusch Dec 23 '09 at 20:22
  • 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. – jvilalta Dec 23 '09 at 21:17