C# 中的多线程是什么?

csharpprogrammingserver side programming更新于 2025/10/14 19:52:17

在 C# 中,System.Threading.Thread 类用于处理线程。它允许在多线程应用程序中创建和访问单个线程。进程中第一个执行的线程称为主线程。

当 C# 程序开始执行时,主线程会自动创建。使用 Thread 类创建的线程称为主线程的子线程。

以下示例展示了如何在 C# 中创建线程 −

using System;
using System.Threading;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Thread th = Thread.CurrentThread;
         th.Name = "MainThread";
         Console.WriteLine("This is {0}", th.Name);
         Console.ReadKey();
      }
   }
}

这是另一个示例,展示如何在 C# 中管理线程 −

示例

using System;
using System.Threading;

namespace MultithreadingApplication {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         Console.WriteLine("Child thread starts");
         // 线程暂停 5000 毫秒
         int sleepfor = 5000;
         Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
         Thread.Sleep(sleepfor);
         Console.WriteLine("Child thread resumes");
      }

      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         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
Child Thread Paused for 5 seconds
Child thread resumes

相关文章