Create multiple threads and wait all of them to complete

前端 未结 8 1897
星月不相逢
星月不相逢 2020-12-02 15:13

How can I create multiple threads and wait for all of them to complete?

相关标签:
8条回答
  • 2020-12-02 15:56

    If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

    Example:

    List<Thread> threads = new List<Thread>();
    
    
    // Start threads
    for(int i = 0; i<10; i++)
    {
        int tmp = i; // Copy value for closure
        Thread t = new Thread(() => Console.WriteLine(tmp));
        t.Start;
        threads.Add(t);
    }
    
    // Await threads
    foreach(Thread thread in threads)
    {
        thread.Join();
    }
    
    0 讨论(0)
  • 2020-12-02 15:57

    In .NET 4.0, you can use the Task Parallel Library.

    In earlier versions, you can create a list of Thread objects in a loop, calling Start on each one, and then make another loop and call Join on each one.

    0 讨论(0)
提交回复
热议问题