0

Suppose, I have a server application. This application polls for incoming clients in a separate child thread. Also, sub-threads are spawned for each of the incoming clients to service their requests separately.

I want to kill all threads except the Server application's main thread, say, by clicking a button.

How can I do that?

user366312
  • 16,949
  • 65
  • 235
  • 452
  • 3
    By creating the threads properly or not at all - tasks are far easier to use. Background threads will be aborted when the main thread exits. In all cases it's *far better* to signal termination gracefully than abort an operation and leave garbage behind – Panagiotis Kanavos Jul 10 '19 at 08:14
  • duplicate: https://stackoverflow.com/questions/12894503/windows-form-application-thread-wont-stop – jazb Jul 10 '19 at 08:15
  • Possible duplicate of [Windows Form Application, Thread won't stop](https://stackoverflow.com/questions/12894503/windows-form-application-thread-wont-stop) – jazb Jul 10 '19 at 08:16
  • Be aware of https://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort – Johnny Jul 10 '19 at 08:16
  • 1
    Why are you asking? I suspect you created a lot of foreground threads and can't shut them down now? You can simplify your code a lot by using high-level constructs like asynchronous programming, tasks, channels or dataflow blocks instead of raw threads – Panagiotis Kanavos Jul 10 '19 at 08:16
  • I agree with the others: if you need to kill your own threads your design is fundamentally wrong. – ckuri Jul 10 '19 at 08:27

1 Answers1

1

This application polls for incoming clients in a separate child thread.

Okay, so it seems you are the one creating those threads. Can't you just keep a list of threads and then call Abort on them all? That seems the most straight-forward approach. (But be aware of some caveats)

If that is not possible, you could get a list of all threads, filter them on their name or some other characteristic, and Abort those.

A better approach is to use tasks, which are far better manageable than threads. You might want to read up on TPL.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325