My app (WinUI 3) is freezing up on this line even though I'm using await
What could I be doing wrong?
24 Replies
await suspends evaluation until whatever you're awaiting completes
Yes but it seems to be locking up the UI thread as well, isn't it not supposed to do that?
where u call Connect u would do configureawait(false)
I assume u call connect from a button in the codebehind of the ui?
It's run in OnLaunched
sure which is an event
can u post the relevant code
also giving you are constantly reading in a loop
even if u use configureawait it would not be ideal
all the code below should be running in a fireandforget task
all this logic
u would also need to rewrite some of your code to make the client available from other methods so u can get the stream.
Like this?
await liberaChat.Connect().ConfigureAwait(false);
it would be that but since you have a loop inside that wont do much in this scenario
I have the loop because I want to keep getting new lines as they become available
yes then re-read all of what I said above
What's the reason?
because otherwise nothing else will run that loop will run until there is no more data to read or is disconnected
it will be there sitting awaiting forever to come back
so instead you move that logic to a fire and forget task which can run indefinitely
I thought
await
allows other stuff to run (e.g. the UI thread) while it's waiting for the function to returnim sorry but its late here to explain the whole idea of how async works
in the context you're presenting it wont and it will hang your ui.
what u would do is, u can go up to calling ConnectAsync the rest would go in a fire and forget task
you have to show what you do with Connect
oh, sorry, the chat didn't scroll
i think to debug this you would want to disable Just My Code and show exactly where it is waiting inside of ReadLineAsync
I fixed the issue. The problem was that I assumed
TcpClient.Connected
returns the current status of the socket, but the actual behavior is that it only represents whether or not the socket was connected at some point in the past. Once the connection was closed, ReadLineAsync()
kept returning immediately, keeping the loop constantly running and blocking everything else.
This updated code now works as expected.also what is NewLine?
are you trying to update controls from before the ui is even rendered
An event in the Server class, that gets fired when a line is sent or received, it's subscribed to by the logger window so it can print those lines
ah ok
you should still be very carefull with the await in the onlaunch
with a infinite loop u should just fire and forget instead
Good point, that way if anything goes wrong it still won't crash everything else, thank you for the advice
and yes that is what the ReadLineAsync does
normally you have a "ping pong" message
to detect if the server / client is still alive
stream.Read usually returns the number of bytes read, so if it ever returns 0 that also indicates the connection was closed.