在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()方法是一个非常有用的方法,可以帮助我们控制线程的执行顺序、等待所有线程执行完毕或设置线程的超时退出。