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))
        {
        }
    }
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Why would you need _"clear thread class (not Task ...)"_ ? That immediately makes it look like an X/Y question. – H H Dec 08 '19 at 08:47
  • `public void WaitAll() { foreach (var t in _threads) t.Join(); }` – Sani Huttunen Dec 08 '19 at 08:50
  • Does this answer your question? [Create multiple threads and wait all of them to complete](https://stackoverflow.com/questions/4190949/create-multiple-threads-and-wait-all-of-them-to-complete) – Sani Huttunen Dec 08 '19 at 08:51
  • I need it for project on FW 3.5 – Денис Макушевский Dec 08 '19 at 08:53
  • In 3.5 you at least have the ThreadPool, but that would make your management very different. Maybe even unnecessary. – H H Dec 08 '19 at 09:02
  • Can't you use this sample code? https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread?view=netframework-4.8 and this for .net 3.5 https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread?view=netframework-3.5 (does not make any difference though) – brainless coder Dec 08 '19 at 09:04
  • Maybe a duplicate, but a clear question und no reason to close for unclearity. – Holger Dec 08 '19 at 09:07

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();
}
H H
  • 263,252
  • 30
  • 330
  • 514