【问题标题】:How to wait for the thread to end before continuing with the program如何在继续程序之前等待线程结束
【发布时间】:2012-11-04 17:51:20
【问题描述】:

我有一个在 C# 中使用线程的简单程序。在我执行Console.ReadKey(); 终止程序之前,如何确保所有线程都已执行完毕(否则它会直接转到ReadKey,我必须按下它才能让线程继续执行)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Partie_3
{
    class Program
    {
        static int _intToManipulate;
        static object _lock;
        static Thread thread1;
        static Thread thread2;

        static void Main(string[] args)
        {
            _intToManipulate = 0;

            _lock = new object();

            thread1 = new Thread(increment);
            thread2 = new Thread(decrement);

            thread1.Start();
            thread2.Start();

            Console.WriteLine("Done");
            Console.ReadKey(true);
        }



        static void increment()
        {
            lock (_lock)
            {
                _intToManipulate++;
                Console.WriteLine("increment : " + _intToManipulate);
            }
        }
        static void decrement()
        {
            lock (_lock)
            {
                _intToManipulate--;
                Console.WriteLine("decrement : " + _intToManipulate);
            }
        }
    }
}

【问题讨论】:

    标签: c# multithreading


    【解决方案1】:

    你正在寻找Thread.Join():

    thread1.Start();
    thread2.Start();
    
    thread1.Join();
    thread2.Join();
    
    Console.WriteLine("Done");
    Console.ReadKey(true);
    

    【讨论】:

    • 也就是说,使用 TPL 可能比手动处理 Thread 对象更明智。
    【解决方案2】:

    可以在这里找到类似的问题:C#: Waiting for all threads to complete

    对于 C# 4.0+,我个人更喜欢使用任务而不是线程并等待它们完成,如第二高投票答案中所述:

    for (int i = 0; i < N; i++)
    {
         tasks[i] = Task.Factory.StartNew(() =>
         {               
              DoThreadStuff(localData);
         });
    }
    while (tasks.Any(t => !t.IsCompleted)) { } //spin wait
    
    Console.WriteLine("All my threads/tasks have completed. Ready to continue");
    

    如果您对线程和任务没有多少经验,我建议您走任务路线。相比之下,它们使用起来真的很简单。

    【讨论】:

      猜你喜欢
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2020-02-01
      相关资源
      最近更新 更多