Asynchronous operations with System.Net.Sockets

G

Guest

I have a couple questions concerning the inner workings of a
System.Net.Socket class when doing asynchronous read/write operations.

1) When a program calls the asynchronous operation BeginRead(..., callback)
or BeginWrite(..., callback), the reading or writing operation obviously runs
on a separate thread created and maintained inside of the the Net.Socket
object. My question is, when the read/write operation completes and the
"callback" gets called, does the code within the callback execute on that
same thread that the Socket created to do the actual reading/writing, or does
it do the callback on separate worker thread created by the socket, thereby
freeing the socket object to handle other calls to BeginRead/Write while the
callback code is executing?

2) On a Net.Socket, after calling BeginWrite(...), if your program calls
BeginWrite(...) again to write more data BEFORE the first BeginWrite
completes and executes the callback (and subsequently calls EndWrite(...)),
will the data in the second BeginWrite be "queued up" by the socket and
automatically send after an EndWrite(...) is called when the first write
completes? You'd think I'd be able to figure this out though trial and error
testing, but my results were somewhat confusing and although calling
BeginWrite a second time before the first BeginWrite completes does not throw
an error, it was hard to tell if the data in-fact was queued by the socket
and send immediately after the first write completed. Because of this I
decided to write a wrapper class that allows requests to write data from
multiple threads, and the class queues each write request on a Queue object
and processes the next queued write after the previous one completes. I'd
much rather not have to use the wrapper class if someone could convince me
the Net.Socket class can queue up the data to write upon each successive call
to BeginWrite.

Thanks,
Nate A
 
F

Feroze [msft]

Yes, when the Callback is executed, it is executed on a separate thread from
the one that initiated the asynchronous operation.

You can queue up as many beginXXX as you want, and they will be completed in
the order they were queued to the OS. If the BeginXXX did not throw an
exception, you can assume that the operation was queued. If a queued
operation fails, then your callback will be invoked and you will get an
exception in the corresponding call to EndXXX().

Does that help?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top