I am trying to use a switch statement to control disconnecting a socket. However, when I change the case from the update function (by getting the X key), the code in the switch statement for the disconnect case does not execute. Please see below if you can!
The Switch statement
The RunSession Function

The Update Function
Functions that invoke RunAsync
Stay away from async void wherever you can. It causes nightmares and will be very confusing when you run and debug it.
For a quick answer, update your async void RunAsync method signature to be async Task RunAsync instead, and then update the code inside ConnectClient to be await RunAsync(); However, I think you may still have some issues because the async code you posted is more complicated than it needs to be, so there could be bugs.
In general, I recommend watching these 6 videos on how to use async/await.

I will certain watch those videos, and will avoid async avoid. However, changing the signatures has revealed a serious problem I have here. I cannot close the connection from that sequence of commands. My read function is awaiting in space and locking up everything so unless the socket finished a read, it cannot be closed from waiting for the result of RunSession, as it always waits for it.
RunAsync is going to get called and essentially immediately return, because it is async.
It’s going to do stuff, but the stuff it does is set state to LISTENING. Switch on that, then call RunSession and wait for that to finish before continuing. Once RunSession returns, RunAsync is essentially going to return.

Is state a class variable?
If so, you might have issues with state being manipulated between multiple threads. Try and keep state to one thread. Have your methods return the state and manage it in a more central location.
As-is your RunAsync method is just setting state = LISTENING and then switching on that value – which will always be LISTENING because you just set it that way. I’m not familiar with socket management but I’m guessing you meant to do that either in the class initialization or immediately after the switch statement to reset the state?

No. The update function should change the global variable state (which is public on the class) to disconnected when you press the key down.
I’m fact when I read to the debugger the state is changing. I wonder if it’s not visible to the function even if that is the case somehow. It’s odd. It’s not critical it work this particular way but it would be pretty darn clean. I’m not blocking anywhere or deadlocking when this runs at least, so there’s that.
Where is “state” declared? How is “RunAsync() supposed to know what “state” was when it forces it to State.LISTENING before it tests it?
The first line of runasync sets the state. It’s the first function here.

source