Ive a question about this example: Asynchronous Client Socket .
It says that the operations are asynchronous and they ARE (beginxxx/endxxx are presented), but they use ManualResetEvent and if i understand the sample code correctly - such calls:
Receive(client);
receiveDone.WaitOne();
Will block the thread, they were called from. So that if i have an application with UI and i call that async socket code from main thread - application will freeze...Or am i wrong? Sorry, i expected to send/receive some commands over tcp asynchronously without freezing main thread. Will i have to call all the socket operations from that sample to avoid freezing?
Yes, this code is set up so that it will run synchronously. However, you can easily use the Beginxxx and Endxxx calls yourself rather than wrapping them as this (poor) example of asynchronous action is written.
For further clarification, the article does run each method asynchronously, but then blocks using blocker.WaitOne(); A better approach to something like this might be to have your beginconnect callback trigger a send, which will have its callback trigger a receive, etc
You could also use the TPL and take advantage of their ContinueWith functionality to do this. Then your code might even look cleaner :)
It would block the UI. The MSDN example does demonstrate asynchronousy, but very poorly. Its also primitive. Please look at this topic which I also just answered regarding different asynchronous programming models. I discuss quite a few and provide links for all of them with full examples.
Link: Need help to implement multithreading in C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With