views:

78

answers:

2

Based on my reading and testing, with asynchronous sockets, the socket itself can be passed using state object (IAsyncResult result), also if store the socket as a private field, it would be captured by the callback methods.

I am wondering how the IAysnResult is kepted between the BeginXXX and ReceiveXXX? It looks to me that after the BeginXXX call and the method ends, the state object would be disposed by GC if there is no reference to it.

In the case of private field, how the private field is shared between threads? (As far as I know, a callback is executed using a thread from the default thread pool, which would be considered as a new thread.)

Many thanks, hope the questions themselves are clear.

+1  A: 

This same thing is described in this stackoverflow answer

Adeel
A: 

GC is not disposing objects, it is releasing memory used by objects with no references. Client code should dispose objects, GC never does that.

IAysnResult still has a reference in a delegate executed in a thread pool, so it woun't be collected by GC unitl a callback method finishes.

Private members are always visible to the executing thread, so your private socket field will be accessable for all threads that are executing methods of the containing class.

Al Bundy