我有这个简单的程序在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);
}
}
}
}
答案 0 :(得分:3)
您正在寻找Thread.Join():
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Done");
Console.ReadKey(true);
答案 1 :(得分:3)
可以在此处找到类似的问题:C#: Waiting for all threads to complete
使用C#4.0+我个人更喜欢使用Tasks而不是Threads并等待它们完成,如第二个最高投票答案所述:
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");
如果你对线程和任务没什么经验,我建议你去做任务路线。相比之下,它们使用起来非常简单。