当前位置:网站首页>了解下C# 多线程

了解下C# 多线程

2022-08-02 08:17:00 nginx

  
 
 
  1. using System;using System.Threading;
  2. namespace MultithreadingApplication
  3. {
  4. class ThreadCreationProgram
  5. {
  6. public static void CallToChildThread()
  7. {
  8. try
  9. {
  10. Console.WriteLine("Child thread starts");
  11. // 计数到 10
  12. for (int counter = 0; counter <= 10; counter++)
  13. {
  14. Thread.Sleep(500);
  15. Console.WriteLine(counter);
  16. }
  17. Console.WriteLine("Child Thread Completed");
  18. }
  19. catch (ThreadAbortException e)
  20. {
  21. Console.WriteLine("Thread Abort Exception");
  22. }
  23. finally
  24. {
  25. Console.WriteLine("Couldn't catch the Thread Exception");
  26. }
  27. }
  28. static void Main(string[] args)
  29. {
  30. ThreadStart childref = new ThreadStart(CallToChildThread);
  31. Console.WriteLine("In Main: Creating the Child thread");
  32. Thread childThread = new Thread(childref);
  33. childThread.Start();
  34. // 停止主线程一段时间
  35. Thread.Sleep(2000);
  36. // 现在中止子线程
  37. Console.WriteLine("In Main: Aborting the Child thread");
  38. childThread.Abort();
  39. Console.ReadKey();
  40. }
  41. }
  42. }

原网站

版权声明
本文为[nginx]所创,转载请带上原文链接,感谢
https://www.openjq.com/thread-35286-1-1.html