c# - 多线程中的等待问题

标签 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?**
            }
        }
    }

我的问题是如何等到“threads”列表中的所有线程完成后再调用 CombineResult 方法?

谢谢

最佳答案

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

private List<Thread> threads = new List<Thread>();

然后用线程填充列表

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

最后,您可以有一个调用 Join 的方法对于列表中的每个线程。设置超时延迟通常是一个好习惯,这样您的程序就不会永远阻塞(以防线程中出现错误)

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


另一种方法是使用 Task 上课并调用 Task.WaitAll

关于c# - 多线程中的等待问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11673742/

相关文章:

java - 为什么 java.lang.Thread 类没有一个只接受 ThreadGroup 的构造函数?

C# XML,查找节点及其所有父节点

c# - db.savechanges() 中的默认超时值?

c# - 线程池 + 轮询 C# .Net 3.5

c# - 在打开表单之前使用 Invoke 时出现 InvalidOperationException

java - 使用 AtomicReference 替换 ReadWriteLock 以实现非阻塞操作

c# - 我需要帮助将 C# 字符串从一种字符编码转换为另一种字符编码吗?

c# - 如何从文本文件中固定这个解析循环

c# - 无法从用法中推断出方法的类型参数

c# - 程序在访问消息队列时挂起