如何在 C# 中创建线程?

csharpprogrammingserver side programming更新于 2025/5/19 18:37:17

线程是轻量级进程。线程被定义为程序的执行路径。通过扩展 Thread 类来创建线程。然后,扩展的 Thread 类调用 Start() 方法来开始子线程的执行。

线程示例:线程使用的一个常见示例是现代操作系统实现并发编程。使用线程可以节省 CPU 周期的浪费并提高应用程序的效率。

以下是显示如何创建线程的示例。

示例

using System;
using System.Threading;
namespace Demo {
   class Program {
      public static void ThreadFunc() {
         Console.WriteLine("Child thread starts");
      }
      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(ThreadFunc);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         Console.ReadKey();
      }
   }
}

输出

In Main: Creating the Child thread
Child thread starts

相关文章