最近开始学习C#的多线程编程的知识,刚开始学习,依葫芦画瓢写了个简单例子,记录一下。
以下是一个简单的 C# 多线程例子,它创建两个线程,每个线程执行不同的任务:
例子:
using System; using System.Threading; // 堆代码 duidaima.com public class MultiThreadExample { public static void Main() { Thread thread1 = new Thread(new ThreadStart(DoTask1)); Thread thread2 = new Thread(new ThreadStart(DoTask2)); thread1.Start(); thread2.Start(); Console.WriteLine("Main thread is waiting for both threads to complete."); thread1.Join(); thread2.Join(); Console.WriteLine("Both threads have completed their tasks."); } public static void DoTask1() { Console.WriteLine("Task 1 is starting."); // 假装执行某些任务 Thread.Sleep(5000); Console.WriteLine("Task 1 has completed."); } public static void DoTask2() { Console.WriteLine("Task 2 is starting."); // 假装执行某些任务 Thread.Sleep(3000); Console.WriteLine("Task 2 has completed."); } }在这个例子中,`Main` 方法创建了两个线程,分别执行 `DoTask1` 和 `DoTask2` 方法。每个任务都会假装执行一些耗时的操作,例如等待 5 秒或 3 秒。在开始执行任务后,`Main` 方法等待两个线程都完成,然后输出一条消息表示两个任务都已完成。