1

I must say that it's probably a bad pattern, but in my sandbox I created an interface that call a background service (that fires a thread and keep it live) every time I click a button.

This is good, cause I can create a chaos situation and found out how the environment will deal with this.

But, otherwise, I'm facing a problem: How can I get all thread currently running and kill them all. Calling GB or something.

1 Answer 1

3

I assume that you don't want a list of all running threads- you want a list of running threads that you started via some particular mechanism, right?

If that's the case, you can do something like this where you start those threads:

List<Thread> myThreads = new List<Thread>(); public void StartAThread() { Thread t = new Thread( ... whatever ...); myThreads.Add(t); t.Start(); } 

Now, assuming that you want to kill those threads with extreme prejudice- that is, you want them dead, now, and you don't care about knock-on effects of leaving work half-done, you can do:

foreach (var t in myThreads) t.Abort(); 
Sign up to request clarification or add additional context in comments.

3 Comments

Yes! I tough about that. But my question aims some way by reflection or something to found out what's running to force a garbage collector.
You don't need to force the garbage collector. Once you cannot reference an object from any running thread, the object is eligible for GC and will be cleaned up automatically. The trick is that first part- make sure that the objects are not reachable by any running thread.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.