在多线程中等待问题

Mav*_*ang 3 c# multithreading

class MultiThreading
{
    public class ThreadClass
    {
        public string InputString { get; private set; }
        public int StartPos { get; private set; }
        public List<SearchAlgorithm.CandidateStr> completeModels;
        public List<SearchAlgorithm.CandidateStr> partialModels;

        public ThreadClass(string s, int sPos)
        {
            InputString = s;
            StartPos = sPos;
            completeModels = new List<SearchAlgorithm.CandidateStr>();
            partialModels = new List<SearchAlgorithm.CandidateStr>();
        }

        public void Run(int strandID)
        {
            Thread t = new Thread(() => this._run(strandID));
            t.Start();
        }

        private void _run(int strandID)
        {
            SearchAlgorithm.SearchInOneDirection(strandID, ref this.completeModels, ref this.partialModels);
        }

        public static void CombineResult(
            List<ThreadClass> tc,
            out List<SearchAlgorithm.CandidateStr> combinedCompleteModels,
            out List<SearchAlgorithm.CandidateStr> combinedPartialModels)
        {
            // combine the result
        }
    }
}

class Program
    {

        static void Main(string s, int strandID)
        {
            int lenCutoff = 10000;
            if (s.Length > lenCutoff)
            {
                var threads = new List<MultiThreading.ThreadClass>();
                for (int i = 0; i <= s.Length; i += lenCutoff)
                {
                    threads.Add(new MultiThreading.ThreadClass(s.Substring(i, lenCutoff), i));
                    threads[threads.Count - 1].Run(strandID);
                }


                **// How can I wait till all thread in threads list to finish?**
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是我怎么能等到"线程"列表中的所有线程完成然后再调用CombineResult方法?

谢谢

ole*_*sii 5

您可以添加List<Thread>结构以记录所有线程

private List<Thread> threads = new List<Thread>();
Run Code Online (Sandbox Code Playgroud)

然后用线程填充列表

public void Run(int strandID)
{
    Thread t = new Thread(() => this._run(strandID));
    t.Start();
    threads.Add(t);
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用一个方法来调用Join列表中的每个线程.通常一个好的做法是有一个超时延迟,所以你的程序不会永远阻塞(如果一个线程中有错误)

public void WaitAll(List<Thread> threads, int maxWaitingTime)
{
    foreach (var thread in threads)
    {
        thread.Join(maxWaitingTime); //throws after timeout expires
    }
}
Run Code Online (Sandbox Code Playgroud)


另一种方法是使用一个Task类并调用Task.WaitAll