In the client software in a separate thread is working with the server. The program in a separate Task sends the file and waits until the server processes and sends the response. If the user wants to close the tcpClient.Close() connection, then an exception is thrown in Task . How correctly in this situation to close the connection?

  • 2
    See the code sample, just closing Socket \ TcpClient - does not throw an exception (unless of course the object is initialized). - Alexis
  • @Alexis The error is not on closing, but on accessing TcpClient in the stream after closing it in the main application thread. I'm interested in the algorithm how to close correctly and break the connection so that the server rolls back the transaction - Stolborez
  • four
    CancellationToken? - Qwertiy

1 answer 1

It is not the business to substitute a bandwagon for your code, killing an object with which another thread is working. Send a signal about the need to finish the work in the running Task (for example, through the CancellationToken ), and let this Task close the TcpClient .