Create multiple threads and wait all of them to complete

前端 未结 8 1981
星月不相逢
星月不相逢 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 threads = new List();
    
    
    // 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();
    }
    

提交回复
热议问题