Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this microsoft asynchronous server example blocking when it shouldnt?

Tags:

.net

vb.net

I am new to VB.net and socket programming and this is a newbie question so please be nice :)

I have read up a dozen articles on creating a simple asynchronous chat server like app. I'm still at the early stages of learning the model in .net, although I am not new to programming.

This Microsoft vb.net and c sharp example is supposed to be an asynchronous server to listen for a client to connect but it BLOCKS my GUI when I copy and paste the code in my vb.net form in the Window Loaded event handler. I don't understand why. It is supposed to be asynchronous. The window just doesn't show until i paste the client code in a different vb.net form and run it . Then the GUi on the server shows. :(

Thanks

like image 741
iAteABug_And_iLiked_it Avatar asked Nov 22 '25 01:11

iAteABug_And_iLiked_it


2 Answers

See that while (true) in StartListening called in main thread? That thing actually totally uses the thread where it was called.

It is still asynchronous. The question is what is asynchronous to what. There is this main method that orchestrates the sockets, and IO is actually asynchronous to it. But the method itself is not necessarily asynchronous to code that is calling it.

like image 70
Andrey Avatar answered Nov 24 '25 14:11

Andrey


Don't call StartListening on the UI thread. Either call it from a new thread or rewrite it to work with a UI thread model. Then it will function asynchronously as expected (but there might be new problems encountered, like cross-thread access).

Note that in the example, the call to StartListening() never returns or the program would exit immediately. That is, the example demonstrates the use of asynchronous operations but wraps these in a "synchronous" console program. It is, after all, a sample and not a component designed to be directly composed.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!