0

我有这个在 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);
            }
        }
    }
}
4

2 回答 2

3

您正在寻找Thread.Join()

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

thread1.Join();
thread2.Join();

Console.WriteLine("Done");
Console.ReadKey(true);
于 2012-11-04T17:59:36.637 回答
3

可以在此处找到类似的问题: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");

如果你对线程和任务没有什么经验,我建议你走任务路线。相比之下,它们使用起来非常简单。

于 2012-11-04T18:03:12.293 回答