Create multiple threads and wait all of them to complete

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

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

8条回答
  •  隐瞒了意图╮
    2020-12-02 15:44

    I've made a very simple extension method to wait for all threads of a collection:

    using System.Collections.Generic;
    using System.Threading;
    
    namespace Extensions
    {
        public static class ThreadExtension
        {
            public static void WaitAll(this IEnumerable threads)
            {
                if(threads!=null)
                {
                    foreach(Thread thread in threads)
                    { thread.Join(); }
                }
            }
        }
    }
    

    Then you simply call:

    List threads=new List();
    // Add your threads to this collection
    threads.WaitAll();
    

提交回复
热议问题