【问题标题】:C# Threading inside for loop [duplicate]C#线程内部for循环[重复]
【发布时间】:2016-03-20 13:45:59
【问题描述】:

我希望在打印结果之前完成 for 循环,在:

        for (int i = 0; i < 5; i++)
        {
            (new System.Threading.Thread(() =>
                {
                    if (TimeTakingMethod())
                    {
                        ++nResult;
                    }
                })).Start();
        }
        Console.WriteLine("Count = " + nResult);

但 Console.WriteLine 不会等待这些线程完成,因为打印是在主线程上完成的。

如果我将其更改为:

        System.Threading.Thread t = new System.Threading.Thread(() =>
            {
                for (int i = 0; i < 5; i++)
                {
                    (new System.Threading.Thread(() =>
                    {
                        if (TimeTakingMethod())
                        {
                            ++nResult;
                        }
                    })).Start();
                }
            });
        t.Start();
        t.Join();
        Console.WriteLine("Count = " + nResult);

仍然无法解决问题,因为不会等待嵌套线程。

有什么简单的解决方案吗?感谢您完成此操作。

【问题讨论】:

  • 这样使用线程有什么意义?你只是等到它完成......
  • 模糊逻辑?我建议你解释一下你在做什么,为什么?没有明显原因的嵌套线程
  • Idos 和 Saleem,等待是因为只有在循环处理之后才应该打印结果。我在那里使用了线程,因为循环的每次迭代都需要时间。我在问题栏中给出的解释是复杂任务的简化版本,因此这个问题可能会使程序看起来不需要多线程。 Crashmstr,我同意,谢谢。该页面上的以下内容以及该页面上给出的其他答案都有帮助: List threads=new List(); //将你的线程添加到这个集合中 threads.WaitAll();
  • TVOHM 和 YottaGinneh,感谢您的回答,这很有帮助。

标签: c# multithreading for-loop nested


【解决方案1】:

你应该存储创建的线程来控制它们,我使用了一个列表。

        int nResult = 0;
        List<Thread> threads = new List<Thread>();

        for (int i = 0; i < 5; i++)
        {

            Thread thread = new System.Threading.Thread(() =>
            {
                if (TimeTakingMethod())
                {
                    ++nResult;
                }
            });
            thread.Start();
            threads.Add(thread);
        }

        foreach (Thread thread in threads)
            thread.Join();

        Console.WriteLine("Count = " + nResult);

【讨论】:

    【解决方案2】:

    如何做到这一点的示例:

    int result = 0;
    Task.WaitAll(Enumerable.Range(0, 5)
        .Select(index => Task.Factory.StartNew(() =>
        {
            // Do thread things...
            Interlocked.Increment(ref result);
        })).ToArray());
    
    Console.WriteLine(result);
    

    需要注意的两个重要事项是Task.WaitAll,这将导致程序等待所有任务完成,然后再继续调用 WriteLine。

    Interlocked.Increment 还允许您安全地增加任何线程的结果。

    【讨论】:

      猜你喜欢
      • 2011-03-23
      • 2013-06-07
      • 2015-03-21
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2011-10-11
      • 2022-07-07
      • 1970-01-01
      相关资源
      最近更新 更多