0

I'm calling tcpListener.AcceptTcpClient() inside its own thread. Because this blocks forever, the thread doesn't exit when my form closes. I tried calling listenThread.Abort(), but the thread doesn't exit. It's stuck on AcceptTcpClient().

How can I get my whole program to shutdown when I close the main form?

xofz
  • 5,600
  • 6
  • 45
  • 63

2 Answers2

5

Set Thread.IsBackgroundThread to true before starting the listener thread. This will prevent it from keeping the process running when all other (non-background) threads have exited.

A likely better (if more complex) solution is to switch to the asynchronous API, as mentioned in the accepted answer to the question that @JohnKoerner linked.

Chris Shain
  • 50,833
  • 6
  • 93
  • 125
2

Two separate problems:

  1. How to stop a thread blocking app exit (dealt with in other answers)

  2. How to unblock blocked Socket method calls (thereby making your code a little more reusable when you're faced with wanting to stop accepting clients but keep the app running)

To allow the thread to exit gracefully, you can call Dispose on the listening socket:

tcpListener.Server.Dispose()

which will cause all blocked operations to fail with a SocketException. Catch this, deal with it and allow the thread to terminate.

spender
  • 117,338
  • 33
  • 229
  • 351