Cancellation option for Connect & Disconnect #185
Replies: 2 comments
-
Hi @ArvindRamaswamy I'm out on PTO this week but will look into it when I return. If you're interested please make the source changes, submit a PR, and I will integrate. Otherwise I can look at it when I return. Cheers, Joel |
Beta Was this translation helpful? Give feedback.
-
I had the same question. I wanted my tcpClient connection on it's own thread, too - and I wanted to update my UI to show connection attempt progress.
Inside CreateTcpClientConnection, I initialize some stuff: Within CreateTcpClientConnection, right after the tcpClient is created and the tcpClientThread is started, I AWAIT my second task using the same cancellation token (cts): In my app, the user can't do anything until the tcpClient is connected, so it's useful to see the connection is "in progress". As soon the await Task.Run returns, I check the cancellation token. That's it - if it was canceled, I Disconnect/Dispose of the tcpClient. Example: I create a tcpClient with ConnectWithRetries value of 20 seconds, and then kick off my thread. Within 5 seconds the user hits a Cancel button which fires the CancellationTokenSource.Cancel(), and in my tasks, the source's associated tokens now have token.IsCancellationRequested as True, and I can act accordingly. My awaited Task.Run returns immediately, and I wipe the tcpClient - I don't have to wait for the tcpClient to finish it's retries - poof, it's gone. You could def write this differently - but use cancellation sources and tokens (ConnectWithRetries uses them internally). ***I had this method to make sure thread exceptions get caught: ***This is my method for updating my UI's connection status label - every second it updates the UI progress: |
Beta Was this translation helpful? Give feedback.
-
Hi, Is there a way to "cancel" a long running "ConnectwithRetries" call from consuming code? Same goes with Disconnect. Reason being, if I initiate a ConnectWithRetries(30000ms) say, and for some reason the connection is not happening fast and say at the end of 10s User wants to "Cancel" the connect operation? Same goes for disconnect. Please help.
Beta Was this translation helpful? Give feedback.
All reactions