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