[英]How to wait for the thread to end before continuing with the program
我有一個使用C#中的線程的簡單程序。 在執行Console.ReadKey();
之前,如何確保所有線程都已執行完畢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);
}
}
}
}
您正在尋找Thread.Join() :
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Done");
Console.ReadKey(true);
在這里可以找到類似的問題: C#:等待所有線程完成
對於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");
如果您對線程和任務的了解很少,建議您沿着“任務”路線進行。 相比之下,它們確實非常易於使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.