Join and Sleep

  • 调用Join方法,就可以等待另一个线程结束。 AB两个线程,如果B.Join() 那就等待B执行完成才执行A。
  • 例子(join) ```csharp using System; using System.Threading;

namespace ThreadTest { class Program { private static Thread thread1, thread2; static void Main() { // 创建两个线程命名并执行 thread1 = new Thread(ThreadProc); thread1.Name = “Thread1”; thread1.Start();

  1. thread2 = new Thread(ThreadProc);
  2. thread2.Name = "Thread2";
  3. thread2.Start();
  4. }
  5. static void ThreadProc()
  6. {
  7. Console.WriteLine("\nCurrent thread:{0}", Thread.CurrentThread.Name);
  8. if (Thread.CurrentThread.Name == "Thread1" && thread2.ThreadState != ThreadState.Unstarted)
  9. {
  10. thread2.Join();
  11. }
  12. Thread.Sleep(2000);
  13. Console.WriteLine("\nCurrent thread:{0}", Thread.CurrentThread.Name);
  14. Console.WriteLine("Thread1:{0}", thread1.ThreadState);
  15. Console.WriteLine("Thread2:{0}\n", thread2.ThreadState);
  16. }
  17. }

}

  1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/1624034/1593094689546-e78426ba-3867-4cf4-a000-11d6dc9edbbd.png#crop=0&crop=0&crop=1&crop=1&height=279&id=Atyaw&margin=%5Bobject%20Object%5D&name=image.png&originHeight=279&originWidth=304&originalType=binary&ratio=1&rotation=0&showTitle=false&size=15959&status=done&style=stroke&title=&width=304)
  2. <a name="7FZOB"></a>
  3. ## 添加超时
  4. - 调用Join的时候,可以设置一个超时,用毫秒或者TimeSpan都可以(Join重载。如果调用Join的时候不带参数是void,带参数的话返回值是bool类型)。
  5. - 如果返回时true,那就是线程结束了;如果超时了就返回false
  6. ```csharp
  7. using System;
  8. using System.Threading;
  9. namespace ThreadTest
  10. {
  11. class Program
  12. {
  13. private static TimeSpan waitTime = new TimeSpan(0, 0, 1);
  14. static void Main()
  15. {
  16. Thread newThread = new Thread(Work);
  17. newThread.Start();
  18. if (newThread.Join(waitTime + waitTime))
  19. {
  20. Console.WriteLine("线程结束.");
  21. }
  22. else
  23. {
  24. Console.WriteLine("连接超时.");
  25. }
  26. }
  27. static void Work()
  28. {
  29. Thread.Sleep(waitTime);
  30. }
  31. }
  32. }
  • Thread.Sleep()方法会暂停当前的线程,并等待一段时间。
  • 注意:
    • Thread.Sleep(0)这样调用会导致线程立即放弃本身当前的时间片,自动将CPU移交给其他线程。
    • Thread,YieId做同样的事情,但是它指挥把执行交给同一处理器上的其它线程。

其它

  • Sleep(0)或YieId有时在高级性能调试的生产代码中很有用。它也是一个很好的诊断工具,有助于发现线程安全问题:
    • 如果在代码中的任何地方插入Thread.YieId就破坏了程序,那么你的程序几乎肯定有bug。