2

I need to use clear thread class (not Task and without async/await). How I can correctly wait of the ends of all task in list?

I want correctly method WaitAll()

For example:

public class TaskManager
{
    private readonly List<Thread> _threads = new List<Thread>();

    public void AddTask([NotNull] Action<int> action, int i)
    {
        var thread = new Thread(() =>
        {
            action(i);
        });
        _threads.Add(thread);
        thread.Start();
    }

    public void WaitAll()
    {
        while (_threads.Any(x => x.ThreadState != ThreadState.Stopped))
        {
        }
    }
}
DiplomacyNotWar
  • 31,605
  • 6
  • 57
  • 75

1 Answers1

1

I question the need for 'bare threads' but when you're sure about that, then waiting in a while-loop is wasting CPU time. Threads only have the Join() method available for this:

public void WaitAll()
{
   foreach(var thread in _threads)    
     thread.Join();
}
Henk Holterman
  • 250,905
  • 30
  • 306
  • 490