public class ManageThread { /// /// Stockage de tous les threads. /// private List allThreads = new List(); /// /// Autorise ou pas les ajout de threads. /// Quand ManageThread est en train de purger tous les threads (via JoinAllThreads()), /// on empêche l'ajout de nouveaux. /// private bool allowAdd = true; /// /// On ajoute un thread à la liste. /// En même temps, on s'assure sur tous les threads de la liste sont bien en vie. /// /// Le nouveau thread. public bool Add(Thread t) { lock (allThreads) { for (int i = allThreads.Count - 1; i >= 0; i--) { if (!allThreads[i].IsAlive) { allThreads.RemoveAt(i); } } if (!allowAdd) return false; allThreads.Add(t); return true; } } /// /// On attend que tous les threads restants s'arrêtent tout seul. /// Si une fonction parallèle en ajoute aussi en boucle, on ne quitte jamais la fonction. /// public void JoinAllThreads() { lock (allThreads) { allowAdd = false; } while (true) { Thread t; lock (allThreads) { if (allThreads.Count == 0) return; t = allThreads[0]; } t.Join(); lock (allThreads) { // Pas RemoveAt(0). allThreads.Remove(t); } } } }