在C#中,Thread.Join()方法用于等待線程執行完畢。以下是一些Thread.Join()使用技巧:
Thread thread1 = new Thread(DoSomething1);
Thread thread2 = new Thread(DoSomething2);
thread1.Start();
thread1.Join();
thread2.Start();
thread2.Join();
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(DoSomething);
threads.Add(thread);
thread.Start();
}
foreach (Thread thread in threads)
{
thread.Join();
}
Thread thread = new Thread(DoSomething);
thread.Start();
if (!thread.Join(1000)) //等待1秒
{
thread.Abort(); //超時退出線程
}
總的來說,Thread.Join()方法是一個非常有用的方法,可以幫助我們控制線程的執行順序、等待所有線程執行完畢或設置線程的超時退出。