活动公告

系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

C#开发者必知线程与进程的区别与应用 掌握多线程编程提升程序性能与用户体验 深入理解NET框架下的并发处理机制

SunJu_FaceMall

3万

主题

2720

科技点

3万

积分

执行版主

碾压王

积分
32881

塔罗立华奏

执行版主 发表于 2025-8-27 15:20:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1. 引言

在现代软件开发中,多线程编程已成为提升应用程序性能和用户体验的关键技术。对于C#开发者而言,深入理解线程与进程的概念、区别以及在.NET框架下的并发处理机制,是构建高效、响应迅速的应用程序的基础。本文将详细探讨这些核心概念,并通过实际代码示例展示如何在C#中应用多线程编程技术。

2. 进程与线程的基本概念

2.1 进程

进程是操作系统进行资源分配和调度的基本单位,是应用程序的执行实例。每个进程都有独立的内存空间、系统资源和执行状态。在Windows系统中,当我们打开一个应用程序(如Word、浏览器等),操作系统就会创建一个进程来运行该应用程序。

进程的主要特点包括:

• 独立性:每个进程有独立的地址空间,一个进程的崩溃不会直接影响其他进程。
• 资源拥有:进程是资源拥有的基本单位,拥有独立的内存、文件句柄等资源。
• 上下文切换开销大:由于进程间的独立性,进程间的切换需要保存和恢复更多的上下文信息,因此开销较大。

在C#中,我们可以通过Process类来与系统进程进行交互:
  1. using System.Diagnostics;
  2. class ProcessExample
  3. {
  4.     static void Main()
  5.     {
  6.         // 获取当前进程
  7.         Process currentProcess = Process.GetCurrentProcess();
  8.         Console.WriteLine($"当前进程ID: {currentProcess.Id}");
  9.         Console.WriteLine($"进程名称: {currentProcess.ProcessName}");
  10.         Console.WriteLine($"启动时间: {currentProcess.StartTime}");
  11.         
  12.         // 启动一个新的进程
  13.         try
  14.         {
  15.             Process notepadProcess = new Process();
  16.             notepadProcess.StartInfo.FileName = "notepad.exe";
  17.             notepadProcess.StartInfo.Arguments = "";
  18.             notepadProcess.Start();
  19.             
  20.             Console.WriteLine($"已启动记事本进程,ID: {notepadProcess.Id}");
  21.             
  22.             // 等待用户输入后关闭进程
  23.             Console.WriteLine("按任意键关闭记事本进程...");
  24.             Console.ReadKey();
  25.             
  26.             if (!notepadProcess.HasExited)
  27.             {
  28.                 notepadProcess.CloseMainWindow();
  29.                 notepadProcess.Close();
  30.             }
  31.         }
  32.         catch (Exception ex)
  33.         {
  34.             Console.WriteLine($"启动进程时出错: {ex.Message}");
  35.         }
  36.     }
  37. }
复制代码

2.2 线程

线程是进程中的一个执行单元,是CPU调度的基本单位。一个进程可以包含多个线程,这些线程共享进程的资源,如内存空间、文件句柄等,但每个线程有独立的执行栈、程序计数器和局部变量。

线程的主要特点包括:

• 轻量级:线程的创建和切换开销远小于进程。
• 共享资源:同一进程内的线程共享进程的资源,使得线程间通信更加方便。
• 并发性:多个线程可以并发执行,提高应用程序的响应性和吞吐量。

在C#中,我们可以通过Thread类来创建和管理线程:
  1. using System;
  2. using System.Threading;
  3. class ThreadExample
  4. {
  5.     static void Main()
  6.     {
  7.         // 获取主线程信息
  8.         Thread mainThread = Thread.CurrentThread;
  9.         Console.WriteLine($"主线程ID: {mainThread.ManagedThreadId}");
  10.         
  11.         // 创建并启动一个新线程
  12.         Thread workerThread = new Thread(WorkerMethod);
  13.         workerThread.Name = "WorkerThread";
  14.         workerThread.Start();
  15.         
  16.         // 主线程继续执行
  17.         for (int i = 0; i < 5; i++)
  18.         {
  19.             Console.WriteLine($"主线程执行: {i}");
  20.             Thread.Sleep(500);
  21.         }
  22.         
  23.         // 等待工作线程完成
  24.         workerThread.Join();
  25.         Console.WriteLine("工作线程已完成,主线程退出。");
  26.     }
  27.    
  28.     static void WorkerMethod()
  29.     {
  30.         Thread currentThread = Thread.CurrentThread;
  31.         Console.WriteLine($"工作线程 {currentThread.Name} 开始执行,ID: {currentThread.ManagedThreadId}");
  32.         
  33.         for (int i = 0; i < 5; i++)
  34.         {
  35.             Console.WriteLine($"工作线程执行: {i}");
  36.             Thread.Sleep(1000);
  37.         }
  38.         
  39.         Console.WriteLine($"工作线程 {currentThread.Name} 执行完成");
  40.     }
  41. }
复制代码

3. 线程与进程的区别

理解线程与进程的区别对于多线程编程至关重要。以下是它们之间的主要区别:

3.1 资源分配

• 进程:操作系统分配资源的基本单位,每个进程有独立的地址空间、代码、数据和资源。
• 线程:CPU调度的基本单位,同一进程内的线程共享进程的资源,包括内存空间、文件句柄等。

3.2 上下文切换

• 进程:上下文切换开销大,需要保存和恢复整个进程的地址空间、寄存器状态等。
• 线程:上下文切换开销小,只需要保存和恢复线程的寄存器状态和栈信息。

3.3 通信方式

• 进程:进程间通信(IPC)需要使用特定的机制,如管道、消息队列、共享内存等,相对复杂。
• 线程:线程间通信可以直接通过共享内存进行,更加简单高效。

3.4 健壮性

• 进程:一个进程的崩溃不会影响其他进程,系统更加稳定。
• 线程:一个线程的崩溃可能导致整个进程的崩溃,稳定性相对较低。

3.5 创建和销毁

• 进程:创建和销毁的开销大,速度慢。
• 线程:创建和销毁的开销小,速度快。

下面通过一个示例来展示进程和线程在资源使用上的区别:
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. class ProcessVsThreadExample
  5. {
  6.     static void Main()
  7.     {
  8.         Console.WriteLine("比较进程和线程的创建开销");
  9.         
  10.         // 测试创建多个进程的开销
  11.         Stopwatch processStopwatch = Stopwatch.StartNew();
  12.         for (int i = 0; i < 5; i++)
  13.         {
  14.             Process process = new Process();
  15.             process.StartInfo.FileName = "notepad.exe";
  16.             process.Start();
  17.             process.CloseMainWindow();
  18.             process.WaitForExit();
  19.         }
  20.         processStopwatch.Stop();
  21.         
  22.         Console.WriteLine($"创建5个进程耗时: {processStopwatch.ElapsedMilliseconds} 毫秒");
  23.         
  24.         // 测试创建多个线程的开销
  25.         Stopwatch threadStopwatch = Stopwatch.StartNew();
  26.         Thread[] threads = new Thread[5];
  27.         for (int i = 0; i < 5; i++)
  28.         {
  29.             threads[i] = new Thread(WorkerMethod);
  30.             threads[i].Start();
  31.         }
  32.         
  33.         // 等待所有线程完成
  34.         foreach (Thread thread in threads)
  35.         {
  36.             thread.Join();
  37.         }
  38.         threadStopwatch.Stop();
  39.         
  40.         Console.WriteLine($"创建5个线程耗时: {threadStopwatch.ElapsedMilliseconds} 毫秒");
  41.     }
  42.    
  43.     static void WorkerMethod()
  44.     {
  45.         // 模拟一些工作
  46.         Thread.Sleep(100);
  47.     }
  48. }
复制代码

4. C#中的线程处理

4.1 Thread类

System.Threading.Thread类是C#中最基本的线程操作类,它提供了创建、控制和管理线程的方法。
  1. using System;
  2. using System.Threading;
  3. class ThreadClassExample
  4. {
  5.     static void Main()
  6.     {
  7.         // 创建线程但不立即启动
  8.         Thread thread = new Thread(new ThreadStart(ExecuteTask));
  9.         
  10.         // 设置线程属性
  11.         thread.Name = "WorkerThread";
  12.         thread.IsBackground = false; // 前台线程
  13.         
  14.         // 启动线程
  15.         thread.Start();
  16.         
  17.         // 检查线程状态
  18.         Console.WriteLine($"线程状态: {thread.ThreadState}");
  19.         
  20.         // 等待线程完成
  21.         thread.Join();
  22.         Console.WriteLine("线程执行完成");
  23.     }
  24.    
  25.     static void ExecuteTask()
  26.     {
  27.         Console.WriteLine($"{Thread.CurrentThread.Name} 开始执行");
  28.         
  29.         // 模拟耗时操作
  30.         for (int i = 0; i < 5; i++)
  31.         {
  32.             Console.WriteLine($"{Thread.CurrentThread.Name} 执行中: {i}");
  33.             Thread.Sleep(500);
  34.         }
  35.         
  36.         Console.WriteLine($"{Thread.CurrentThread.Name} 执行完成");
  37.     }
  38. }
复制代码

4.2 线程池

线程池是一种基于池化思想管理线程的技术,它可以避免频繁创建和销毁线程所带来的开销。在.NET中,ThreadPool类提供了对线程池的访问。
  1. using System;
  2. using System.Threading;
  3. class ThreadPoolExample
  4. {
  5.     static void Main()
  6.     {
  7.         // 获取线程池信息
  8.         int workerThreads;
  9.         int completionPortThreads;
  10.         ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
  11.         Console.WriteLine($"最大工作线程数: {workerThreads}");
  12.         Console.WriteLine($"最大I/O线程数: {completionPortThreads}");
  13.         
  14.         // 使用线程池执行任务
  15.         for (int i = 0; i < 5; i++)
  16.         {
  17.             int taskNum = i;
  18.             ThreadPool.QueueUserWorkItem(state =>
  19.             {
  20.                 Console.WriteLine($"任务 {taskNum} 在线程池线程上执行,线程ID: {Thread.CurrentThread.ManagedThreadId}");
  21.                 Thread.Sleep(1000);
  22.                 Console.WriteLine($"任务 {taskNum} 完成");
  23.             });
  24.         }
  25.         
  26.         // 等待所有任务完成
  27.         Console.WriteLine("按任意键退出...");
  28.         Console.ReadKey();
  29.     }
  30. }
复制代码

4.3 Task类

.NET Framework 4引入了System.Threading.Tasks命名空间,提供了更高级的抽象来表示异步操作。Task类是任务并行库(TPL)的核心,它提供了比直接使用Thread或ThreadPool更简单、更强大的API。
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. class TaskExample
  5. {
  6.     static void Main()
  7.     {
  8.         // 创建并启动一个Task
  9.         Task task1 = Task.Run(() =>
  10.         {
  11.             Console.WriteLine($"Task 1 在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
  12.             Thread.Sleep(1000);
  13.             Console.WriteLine("Task 1 完成");
  14.         });
  15.         
  16.         // 创建并启动一个带返回值的Task
  17.         Task<int> task2 = Task.Run(() =>
  18.         {
  19.             Console.WriteLine($"Task 2 在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
  20.             Thread.Sleep(1500);
  21.             return 42;
  22.         });
  23.         
  24.         // 使用ContinueWith在任务完成后继续执行
  25.         task1.ContinueWith(t =>
  26.         {
  27.             Console.WriteLine("Task 1 的后续操作");
  28.         });
  29.         
  30.         // 等待所有任务完成
  31.         Task.WaitAll(task1, task2);
  32.         
  33.         // 获取Task的结果
  34.         Console.WriteLine($"Task 2 的结果: {task2.Result}");
  35.         
  36.         // 使用Task.Factory创建任务
  37.         Task task3 = Task.Factory.StartNew(() =>
  38.         {
  39.             Console.WriteLine($"Task 3 在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
  40.             Thread.Sleep(500);
  41.             Console.WriteLine("Task 3 完成");
  42.         });
  43.         
  44.         task3.Wait();
  45.         Console.WriteLine("所有任务完成");
  46.     }
  47. }
复制代码

4.4 async/await模式

C# 5引入了async和await关键字,使得异步编程更加直观和简洁。这种模式特别适合I/O密集型操作。
  1. using System;
  2. using System.Net.Http;
  3. using System.Threading.Tasks;
  4. class AsyncAwaitExample
  5. {
  6.     static async Task Main(string[] args)
  7.     {
  8.         Console.WriteLine("开始执行异步操作");
  9.         
  10.         // 调用异步方法
  11.         string result = await DownloadContentAsync("https://www.example.com");
  12.         Console.WriteLine($"下载的内容长度: {result.Length}");
  13.         
  14.         Console.WriteLine("按任意键退出...");
  15.         Console.ReadKey();
  16.     }
  17.    
  18.     static async Task<string> DownloadContentAsync(string url)
  19.     {
  20.         using (HttpClient client = new HttpClient())
  21.         {
  22.             Console.WriteLine("开始下载内容...");
  23.             
  24.             // 异步下载内容
  25.             string content = await client.GetStringAsync(url);
  26.             
  27.             Console.WriteLine("内容下载完成");
  28.             return content;
  29.         }
  30.     }
  31. }
复制代码

5. .NET框架下的并发处理机制

5.1 同步原语

在多线程编程中,同步原语用于控制多个线程对共享资源的访问,防止数据竞争和不一致。

lock语句是C#中最简单的同步机制,用于确保代码块在同一时间只能被一个线程执行。
  1. using System;
  2. using System.Threading;
  3. class LockExample
  4. {
  5.     private static readonly object _lockObject = new object();
  6.     private static int _counter = 0;
  7.    
  8.     static void Main()
  9.     {
  10.         // 创建多个线程来增加计数器
  11.         Thread[] threads = new Thread[10];
  12.         for (int i = 0; i < threads.Length; i++)
  13.         {
  14.             threads[i] = new Thread(IncrementCounter);
  15.             threads[i].Start();
  16.         }
  17.         
  18.         // 等待所有线程完成
  19.         foreach (Thread thread in threads)
  20.         {
  21.             thread.Join();
  22.         }
  23.         
  24.         Console.WriteLine($"最终计数器值: {_counter}");
  25.     }
  26.    
  27.     static void IncrementCounter()
  28.     {
  29.         for (int i = 0; i < 1000; i++)
  30.         {
  31.             // 使用lock确保对_counter的原子操作
  32.             lock (_lockObject)
  33.             {
  34.                 _counter++;
  35.             }
  36.         }
  37.     }
  38. }
复制代码

Monitor类提供了更细粒度的控制,包括尝试获取锁而不阻塞、指定超时等。
  1. using System;
  2. using System.Threading;
  3. class MonitorExample
  4. {
  5.     private static readonly object _lockObject = new object();
  6.     private static int _sharedResource = 0;
  7.    
  8.     static void Main()
  9.     {
  10.         Thread thread1 = new Thread(() => AccessResource("Thread1"));
  11.         Thread thread2 = new Thread(() => AccessResource("Thread2"));
  12.         
  13.         thread1.Start();
  14.         thread2.Start();
  15.         
  16.         thread1.Join();
  17.         thread2.Join();
  18.         
  19.         Console.WriteLine($"最终资源值: {_sharedResource}");
  20.     }
  21.    
  22.     static void AccessResource(string threadName)
  23.     {
  24.         Console.WriteLine($"{threadName} 尝试获取锁...");
  25.         
  26.         // 尝试获取锁,最多等待1秒
  27.         if (Monitor.TryEnter(_lockObject, 1000))
  28.         {
  29.             try
  30.             {
  31.                 Console.WriteLine($"{threadName} 获取了锁,正在访问资源...");
  32.                
  33.                 // 模拟工作
  34.                 for (int i = 0; i < 5; i++)
  35.                 {
  36.                     _sharedResource++;
  37.                     Console.WriteLine($"{threadName} 更新资源为: {_sharedResource}");
  38.                     Thread.Sleep(500);
  39.                 }
  40.             }
  41.             finally
  42.             {
  43.                 // 确保锁被释放
  44.                 Monitor.Exit(_lockObject);
  45.                 Console.WriteLine($"{threadName} 释放了锁");
  46.             }
  47.         }
  48.         else
  49.         {
  50.             Console.WriteLine($"{threadName} 无法获取锁,超时");
  51.         }
  52.     }
  53. }
复制代码

Mutex(互斥体)是一种同步原语,可以用于进程间同步。
  1. using System;
  2. using System.Threading;
  3. class MutexExample
  4. {
  5.     // 创建一个命名的Mutex,可用于跨进程同步
  6.     private static Mutex _mutex = new Mutex(false, "MyNamedMutex");
  7.    
  8.     static void Main()
  9.     {
  10.         Console.WriteLine("应用程序启动,尝试获取互斥体...");
  11.         
  12.         // 尝试获取互斥体
  13.         if (_mutex.WaitOne(3000))
  14.         {
  15.             try
  16.             {
  17.                 Console.WriteLine("获取互斥体成功,执行关键操作...");
  18.                
  19.                 // 模拟关键操作
  20.                 for (int i = 0; i < 5; i++)
  21.                 {
  22.                     Console.WriteLine($"执行操作: {i + 1}/5");
  23.                     Thread.Sleep(1000);
  24.                 }
  25.             }
  26.             finally
  27.             {
  28.                 // 释放互斥体
  29.                 _mutex.ReleaseMutex();
  30.                 Console.WriteLine("互斥体已释放");
  31.             }
  32.         }
  33.         else
  34.         {
  35.             Console.WriteLine("获取互斥体失败,可能另一个实例正在运行");
  36.         }
  37.         
  38.         Console.WriteLine("按任意键退出...");
  39.         Console.ReadKey();
  40.     }
  41. }
复制代码

Semaphore(信号量)用于限制同时访问某一资源的线程数量。
  1. using System;
  2. using System.Threading;
  3. class SemaphoreExample
  4. {
  5.     // 创建一个信号量,最多允许3个线程同时访问
  6.     private static Semaphore _semaphore = new Semaphore(3, 3);
  7.    
  8.     static void Main()
  9.     {
  10.         // 创建并启动10个工作线程
  11.         for (int i = 0; i < 10; i++)
  12.         {
  13.             int threadNum = i;
  14.             Thread workerThread = new Thread(() => AccessResource(threadNum));
  15.             workerThread.Name = $"Thread {i}";
  16.             workerThread.Start();
  17.         }
  18.         
  19.         Console.WriteLine("按任意键退出...");
  20.         Console.ReadKey();
  21.     }
  22.    
  23.     static void AccessResource(int threadNum)
  24.     {
  25.         Console.WriteLine($"线程 {threadNum} 等待访问资源...");
  26.         
  27.         // 等待信号量
  28.         _semaphore.WaitOne();
  29.         
  30.         try
  31.         {
  32.             Console.WriteLine($"线程 {threadNum} 获得访问权限,正在使用资源...");
  33.             
  34.             // 模拟使用资源
  35.             Thread.Sleep(2000);
  36.             
  37.             Console.WriteLine($"线程 {threadNum} 完成资源使用");
  38.         }
  39.         finally
  40.         {
  41.             // 释放信号量
  42.             _semaphore.Release();
  43.         }
  44.     }
  45. }
复制代码

5.2 线程安全集合

.NET Framework提供了一些线程安全的集合类,用于在多线程环境中安全地操作数据。

ConcurrentDictionary是线程安全的字典集合。
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. class ConcurrentDictionaryExample
  6. {
  7.     static void Main()
  8.     {
  9.         // 创建线程安全的字典
  10.         ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
  11.         
  12.         // 创建多个任务并发操作字典
  13.         Task[] tasks = new Task[10];
  14.         for (int i = 0; i < tasks.Length; i++)
  15.         {
  16.             int taskNum = i;
  17.             tasks[i] = Task.Run(() =>
  18.             {
  19.                 for (int j = 0; j < 100; j++)
  20.                 {
  21.                     string key = $"Key-{taskNum}-{j}";
  22.                     
  23.                     // 使用AddOrUpdate确保线程安全
  24.                     dictionary.AddOrUpdate(key, 1, (k, v) => v + 1);
  25.                     
  26.                     // 模拟一些工作
  27.                     Thread.Sleep(10);
  28.                 }
  29.             });
  30.         }
  31.         
  32.         // 等待所有任务完成
  33.         Task.WaitAll(tasks);
  34.         
  35.         // 输出结果
  36.         Console.WriteLine($"字典中的项数: {dictionary.Count}");
  37.         
  38.         // 检查一些特定键的值
  39.         for (int i = 0; i < 3; i++)
  40.         {
  41.             string key = $"Key-{i}-0";
  42.             if (dictionary.TryGetValue(key, out int value))
  43.             {
  44.                 Console.WriteLine($"{key} 的值: {value}");
  45.             }
  46.         }
  47.     }
  48. }
复制代码

ConcurrentQueue是线程安全的先进先出(FIFO)集合。
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. class ConcurrentQueueExample
  6. {
  7.     static void Main()
  8.     {
  9.         // 创建线程安全的队列
  10.         ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
  11.         
  12.         // 创建生产者任务
  13.         Task producer = Task.Run(() =>
  14.         {
  15.             for (int i = 0; i < 100; i++)
  16.             {
  17.                 queue.Enqueue(i);
  18.                 Console.WriteLine($"生产: {i}");
  19.                 Thread.Sleep(50);
  20.             }
  21.         });
  22.         
  23.         // 创建消费者任务
  24.         Task consumer = Task.Run(() =>
  25.         {
  26.             int value;
  27.             while (true)
  28.             {
  29.                 if (queue.TryDequeue(out value))
  30.                 {
  31.                     Console.WriteLine($"消费: {value}");
  32.                     Thread.Sleep(100);
  33.                 }
  34.                 else if (producer.IsCompleted)
  35.                 {
  36.                     break;
  37.                 }
  38.             }
  39.         });
  40.         
  41.         // 等待所有任务完成
  42.         Task.WaitAll(producer, consumer);
  43.         
  44.         Console.WriteLine($"队列中的剩余项数: {queue.Count}");
  45.     }
  46. }
复制代码

5.3 并行编程

.NET Framework提供了并行编程支持,可以充分利用多核处理器的计算能力。

Parallel类提供了数据并行和任务并行的简化方法。
  1. using System;
  2. using System.Threading.Tasks;
  3. class ParallelExample
  4. {
  5.     static void Main()
  6.     {
  7.         // 使用Parallel.For进行数据并行
  8.         Console.WriteLine("Parallel.For 示例:");
  9.         Parallel.For(0, 10, i =>
  10.         {
  11.             Console.WriteLine($"迭代 {i} 在线程 {Task.CurrentId} 上执行");
  12.             Task.Delay(100).Wait(); // 模拟工作
  13.         });
  14.         
  15.         Console.WriteLine();
  16.         
  17.         // 使用Parallel.ForEach进行数据并行
  18.         Console.WriteLine("Parallel.ForEach 示例:");
  19.         string[] items = { "A", "B", "C", "D", "E" };
  20.         Parallel.ForEach(items, item =>
  21.         {
  22.             Console.WriteLine($"处理 {item} 在线程 {Task.CurrentId} 上执行");
  23.             Task.Delay(100).Wait(); // 模拟工作
  24.         });
  25.         
  26.         Console.WriteLine();
  27.         
  28.         // 使用Parallel.Invoke进行任务并行
  29.         Console.WriteLine("Parallel.Invoke 示例:");
  30.         Parallel.Invoke(
  31.             () => {
  32.                 Console.WriteLine($"任务1 在线程 {Task.CurrentId} 上执行");
  33.                 Task.Delay(500).Wait();
  34.             },
  35.             () => {
  36.                 Console.WriteLine($"任务2 在线程 {Task.CurrentId} 上执行");
  37.                 Task.Delay(300).Wait();
  38.             },
  39.             () => {
  40.                 Console.WriteLine($"任务3 在线程 {Task.CurrentId} 上执行");
  41.                 Task.Delay(400).Wait();
  42.             }
  43.         );
  44.         
  45.         Console.WriteLine("所有并行操作完成");
  46.     }
  47. }
复制代码

PLINQ是LINQ的并行实现,可以自动并行化查询操作。
  1. using System;
  2. using System.Linq;
  3. class PLINQExample
  4. {
  5.     static void Main()
  6.     {
  7.         // 创建一个大数组
  8.         int[] numbers = Enumerable.Range(1, 10000000).ToArray();
  9.         
  10.         Console.WriteLine("开始处理大数据集...");
  11.         
  12.         // 使用普通LINQ查询
  13.         var linqStartTime = DateTime.Now;
  14.         var linqResult = numbers.Where(n => n % 2 == 0)
  15.                                .Select(n => n * 2)
  16.                                .Take(100)
  17.                                .ToList();
  18.         var linqEndTime = DateTime.Now;
  19.         
  20.         Console.WriteLine($"LINQ处理时间: {(linqEndTime - linqStartTime).TotalMilliseconds} 毫秒");
  21.         
  22.         // 使用PLINQ并行查询
  23.         var plinqStartTime = DateTime.Now;
  24.         var plinqResult = numbers.AsParallel()
  25.                                 .Where(n => n % 2 == 0)
  26.                                 .Select(n => n * 2)
  27.                                 .Take(100)
  28.                                 .ToList();
  29.         var plinqEndTime = DateTime.Now;
  30.         
  31.         Console.WriteLine($"PLINQ处理时间: {(plinqEndTime - plinqStartTime).TotalMilliseconds} 毫秒");
  32.         
  33.         // 验证结果是否相同
  34.         Console.WriteLine($"结果相同: {linqResult.SequenceEqual(plinqResult)}");
  35.         
  36.         // 使用WithDegreeOfParallelism控制并行度
  37.         var controlledStartTime = DateTime.Now;
  38.         var controlledResult = numbers.AsParallel()
  39.                                      .WithDegreeOfParallelism(4) // 限制最多使用4个处理器
  40.                                      .Where(n => n % 2 == 0)
  41.                                      .Select(n => n * 2)
  42.                                      .Take(100)
  43.                                      .ToList();
  44.         var controlledEndTime = DateTime.Now;
  45.         
  46.         Console.WriteLine($"控制并行度的PLINQ处理时间: {(controlledEndTime - controlledStartTime).TotalMilliseconds} 毫秒");
  47.         
  48.         // 使用AsOrdered保持原始顺序
  49.         var orderedStartTime = DateTime.Now;
  50.         var orderedResult = numbers.AsParallel()
  51.                                  .AsOrdered() // 保持原始顺序
  52.                                  .Where(n => n % 2 == 0)
  53.                                  .Select(n => n * 2)
  54.                                  .Take(100)
  55.                                  .ToList();
  56.         var orderedEndTime = DateTime.Now;
  57.         
  58.         Console.WriteLine($"保持顺序的PLINQ处理时间: {(orderedEndTime - orderedStartTime).TotalMilliseconds} 毫秒");
  59.     }
  60. }
复制代码

6. 多线程编程的应用场景

6.1 GUI应用程序

在GUI应用程序中,使用多线程可以避免界面冻结,提高用户体验。
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using System.Windows.Forms;
  5. namespace GUIExample
  6. {
  7.     public partial class MainForm : Form
  8.     {
  9.         public MainForm()
  10.         {
  11.             InitializeComponent();
  12.         }
  13.         
  14.         private void btnProcess_Click(object sender, EventArgs e)
  15.         {
  16.             // 禁用按钮,防止重复点击
  17.             btnProcess.Enabled = false;
  18.             
  19.             // 显示进度条
  20.             progressBar.Visible = true;
  21.             progressBar.Value = 0;
  22.             
  23.             // 使用Task.Run在后台线程执行耗时操作
  24.             Task.Run(() =>
  25.             {
  26.                 for (int i = 0; i <= 100; i++)
  27.                 {
  28.                     // 模拟耗时操作
  29.                     Thread.Sleep(100);
  30.                     
  31.                     // 更新UI(必须使用Control.Invoke或Control.BeginInvoke)
  32.                     this.Invoke((MethodInvoker)delegate
  33.                     {
  34.                         progressBar.Value = i;
  35.                         lblStatus.Text = $"处理进度: {i}%";
  36.                     });
  37.                 }
  38.                
  39.                 // 操作完成后更新UI
  40.                 this.Invoke((MethodInvoker)delegate
  41.                 {
  42.                     lblStatus.Text = "处理完成!";
  43.                     btnProcess.Enabled = true;
  44.                 });
  45.             });
  46.         }
  47.     }
  48. }
复制代码

6.2 服务器应用程序

在服务器应用程序中,多线程可以同时处理多个客户端请求,提高服务器的吞吐量。
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. class ServerExample
  7. {
  8.     private static bool _isRunning = false;
  9.     private static TcpListener _listener;
  10.    
  11.     static void Main()
  12.     {
  13.         // 启动服务器
  14.         StartServer(8888);
  15.         
  16.         Console.WriteLine("服务器已启动,按Q键停止服务器...");
  17.         
  18.         // 等待用户输入以停止服务器
  19.         while (Console.ReadKey().Key != ConsoleKey.Q) { }
  20.         
  21.         // 停止服务器
  22.         StopServer();
  23.     }
  24.    
  25.     static void StartServer(int port)
  26.     {
  27.         _listener = new TcpListener(IPAddress.Any, port);
  28.         _listener.Start();
  29.         _isRunning = true;
  30.         
  31.         // 创建一个线程来监听客户端连接
  32.         Thread listenerThread = new Thread(() =>
  33.         {
  34.             while (_isRunning)
  35.             {
  36.                 try
  37.                 {
  38.                     // 接受客户端连接
  39.                     TcpClient client = _listener.AcceptTcpClient();
  40.                     Console.WriteLine("客户端已连接");
  41.                     
  42.                     // 为每个客户端创建一个处理线程
  43.                     Thread clientThread = new Thread(() => HandleClient(client));
  44.                     clientThread.Start();
  45.                 }
  46.                 catch (Exception ex)
  47.                 {
  48.                     Console.WriteLine($"监听错误: {ex.Message}");
  49.                 }
  50.             }
  51.         });
  52.         
  53.         listenerThread.Start();
  54.     }
  55.    
  56.     static void StopServer()
  57.     {
  58.         _isRunning = false;
  59.         _listener?.Stop();
  60.         Console.WriteLine("服务器已停止");
  61.     }
  62.    
  63.     static void HandleClient(TcpClient client)
  64.     {
  65.         try
  66.         {
  67.             using (NetworkStream stream = client.GetStream())
  68.             {
  69.                 byte[] buffer = new byte[1024];
  70.                 int bytesRead;
  71.                
  72.                 // 读取客户端发送的数据
  73.                 bytesRead = stream.Read(buffer, 0, buffer.Length);
  74.                 string clientMessage = Encoding.ASCII.GetString(buffer, 0, bytesRead);
  75.                 Console.WriteLine($"收到消息: {clientMessage}");
  76.                
  77.                 // 处理请求(模拟耗时操作)
  78.                 Thread.Sleep(1000);
  79.                
  80.                 // 发送响应
  81.                 string response = $"服务器响应: {clientMessage.ToUpper()}";
  82.                 byte[] responseBytes = Encoding.ASCII.GetBytes(response);
  83.                 stream.Write(responseBytes, 0, responseBytes.Length);
  84.                 Console.WriteLine($"已发送响应: {response}");
  85.             }
  86.         }
  87.         catch (Exception ex)
  88.         {
  89.             Console.WriteLine($"处理客户端时出错: {ex.Message}");
  90.         }
  91.         finally
  92.         {
  93.             client.Close();
  94.             Console.WriteLine("客户端连接已关闭");
  95.         }
  96.     }
  97. }
复制代码

6.3 并行计算

对于计算密集型任务,使用多线程可以充分利用多核处理器的计算能力。
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading.Tasks;
  4. class ParallelComputingExample
  5. {
  6.     static void Main()
  7.     {
  8.         // 创建大型矩阵
  9.         int size = 1000;
  10.         double[,] matrixA = GenerateRandomMatrix(size, size);
  11.         double[,] matrixB = GenerateRandomMatrix(size, size);
  12.         
  13.         // 串行矩阵乘法
  14.         var serialStopwatch = Stopwatch.StartNew();
  15.         double[,] serialResult = SerialMatrixMultiply(matrixA, matrixB);
  16.         serialStopwatch.Stop();
  17.         Console.WriteLine($"串行矩阵乘法耗时: {serialStopwatch.ElapsedMilliseconds} 毫秒");
  18.         
  19.         // 并行矩阵乘法
  20.         var parallelStopwatch = Stopwatch.StartNew();
  21.         double[,] parallelResult = ParallelMatrixMultiply(matrixA, matrixB);
  22.         parallelStopwatch.Stop();
  23.         Console.WriteLine($"并行矩阵乘法耗时: {parallelStopwatch.ElapsedMilliseconds} 毫秒");
  24.         
  25.         // 验证结果是否相同
  26.         bool resultsEqual = true;
  27.         for (int i = 0; i < size; i++)
  28.         {
  29.             for (int j = 0; j < size; j++)
  30.             {
  31.                 if (Math.Abs(serialResult[i, j] - parallelResult[i, j]) > 0.000001)
  32.                 {
  33.                     resultsEqual = false;
  34.                     break;
  35.                 }
  36.             }
  37.             if (!resultsEqual) break;
  38.         }
  39.         
  40.         Console.WriteLine($"结果相同: {resultsEqual}");
  41.         Console.WriteLine($"加速比: {(double)serialStopwatch.ElapsedMilliseconds / parallelStopwatch.ElapsedMilliseconds:F2}x");
  42.     }
  43.    
  44.     // 生成随机矩阵
  45.     static double[,] GenerateRandomMatrix(int rows, int cols)
  46.     {
  47.         double[,] matrix = new double[rows, cols];
  48.         Random random = new Random();
  49.         
  50.         for (int i = 0; i < rows; i++)
  51.         {
  52.             for (int j = 0; j < cols; j++)
  53.             {
  54.                 matrix[i, j] = random.NextDouble() * 100;
  55.             }
  56.         }
  57.         
  58.         return matrix;
  59.     }
  60.    
  61.     // 串行矩阵乘法
  62.     static double[,] SerialMatrixMultiply(double[,] matrixA, double[,] matrixB)
  63.     {
  64.         int aRows = matrixA.GetLength(0);
  65.         int aCols = matrixA.GetLength(1);
  66.         int bCols = matrixB.GetLength(1);
  67.         
  68.         double[,] result = new double[aRows, bCols];
  69.         
  70.         for (int i = 0; i < aRows; i++)
  71.         {
  72.             for (int j = 0; j < bCols; j++)
  73.             {
  74.                 for (int k = 0; k < aCols; k++)
  75.                 {
  76.                     result[i, j] += matrixA[i, k] * matrixB[k, j];
  77.                 }
  78.             }
  79.         }
  80.         
  81.         return result;
  82.     }
  83.    
  84.     // 并行矩阵乘法
  85.     static double[,] ParallelMatrixMultiply(double[,] matrixA, double[,] matrixB)
  86.     {
  87.         int aRows = matrixA.GetLength(0);
  88.         int aCols = matrixA.GetLength(1);
  89.         int bCols = matrixB.GetLength(1);
  90.         
  91.         double[,] result = new double[aRows, bCols];
  92.         
  93.         // 使用Parallel.For并行计算
  94.         Parallel.For(0, aRows, i =>
  95.         {
  96.             for (int j = 0; j < bCols; j++)
  97.             {
  98.                 for (int k = 0; k < aCols; k++)
  99.                 {
  100.                     result[i, j] += matrixA[i, k] * matrixB[k, j];
  101.                 }
  102.             }
  103.         });
  104.         
  105.         return result;
  106.     }
  107. }
复制代码

7. 多线程编程的最佳实践

7.1 避免死锁

死锁是多线程编程中的常见问题,当两个或多个线程互相等待对方释放资源时,就会发生死锁。
  1. using System;
  2. using System.Threading;
  3. class DeadlockExample
  4. {
  5.     private static readonly object _lock1 = new object();
  6.     private static readonly object _lock2 = new object();
  7.    
  8.     static void Main()
  9.     {
  10.         // 创建两个线程,它们以不同的顺序获取锁
  11.         Thread thread1 = new Thread(() =>
  12.         {
  13.             Console.WriteLine("线程1: 尝试获取lock1...");
  14.             lock (_lock1)
  15.             {
  16.                 Console.WriteLine("线程1: 获取了lock1");
  17.                 Thread.Sleep(100); // 增加死锁发生的概率
  18.                
  19.                 Console.WriteLine("线程1: 尝试获取lock2...");
  20.                 lock (_lock2)
  21.                 {
  22.                     Console.WriteLine("线程1: 获取了lock1和lock2");
  23.                 }
  24.             }
  25.         });
  26.         
  27.         Thread thread2 = new Thread(() =>
  28.         {
  29.             Console.WriteLine("线程2: 尝试获取lock2...");
  30.             lock (_lock2)
  31.             {
  32.                 Console.WriteLine("线程2: 获取了lock2");
  33.                 Thread.Sleep(100); // 增加死锁发生的概率
  34.                
  35.                 Console.WriteLine("线程2: 尝试获取lock1...");
  36.                 lock (_lock1)
  37.                 {
  38.                     Console.WriteLine("线程2: 获取了lock1和lock2");
  39.                 }
  40.             }
  41.         });
  42.         
  43.         thread1.Start();
  44.         thread2.Start();
  45.         
  46.         // 设置超时,防止程序无限期等待
  47.         if (!thread1.Join(5000))
  48.         {
  49.             Console.WriteLine("线程1可能已死锁");
  50.         }
  51.         
  52.         if (!thread2.Join(5000))
  53.         {
  54.             Console.WriteLine("线程2可能已死锁");
  55.         }
  56.         
  57.         Console.WriteLine("主线程退出");
  58.     }
  59. }
复制代码

避免死锁的最佳实践:

1. 始终以相同的顺序获取多个锁。
2. 使用Monitor.TryEnter而不是lock语句,并指定超时。
3. 尽量减少锁的持有时间。
4. 使用更高级的同步机制,如Mutex、Semaphore等。

7.2 减少锁的粒度

锁的粒度指的是被锁保护的代码范围或数据范围。减少锁的粒度可以提高并发性能。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. class LockGranularityExample
  6. {
  7.     // 粗粒度锁示例
  8.     class CoarseGrainedBankAccount
  9.     {
  10.         private readonly object _lock = new object();
  11.         private decimal _balance;
  12.         private List<string> _transactionHistory = new List<string>();
  13.         
  14.         public void Deposit(decimal amount)
  15.         {
  16.             lock (_lock)
  17.             {
  18.                 _balance += amount;
  19.                 _transactionHistory.Add($"存款: +{amount}");
  20.             }
  21.         }
  22.         
  23.         public void Withdraw(decimal amount)
  24.         {
  25.             lock (_lock)
  26.             {
  27.                 _balance -= amount;
  28.                 _transactionHistory.Add($"取款: -{amount}");
  29.             }
  30.         }
  31.         
  32.         public decimal GetBalance()
  33.         {
  34.             lock (_lock)
  35.             {
  36.                 return _balance;
  37.             }
  38.         }
  39.         
  40.         public List<string> GetTransactionHistory()
  41.         {
  42.             lock (_lock)
  43.             {
  44.                 return new List<string>(_transactionHistory);
  45.             }
  46.         }
  47.     }
  48.    
  49.     // 细粒度锁示例
  50.     class FineGrainedBankAccount
  51.     {
  52.         private readonly object _balanceLock = new object();
  53.         private readonly object _historyLock = new object();
  54.         private decimal _balance;
  55.         private List<string> _transactionHistory = new List<string>();
  56.         
  57.         public void Deposit(decimal amount)
  58.         {
  59.             lock (_balanceLock)
  60.             {
  61.                 _balance += amount;
  62.             }
  63.             
  64.             lock (_historyLock)
  65.             {
  66.                 _transactionHistory.Add($"存款: +{amount}");
  67.             }
  68.         }
  69.         
  70.         public void Withdraw(decimal amount)
  71.         {
  72.             lock (_balanceLock)
  73.             {
  74.                 _balance -= amount;
  75.             }
  76.             
  77.             lock (_historyLock)
  78.             {
  79.                 _transactionHistory.Add($"取款: -{amount}");
  80.             }
  81.         }
  82.         
  83.         public decimal GetBalance()
  84.         {
  85.             lock (_balanceLock)
  86.             {
  87.                 return _balance;
  88.             }
  89.         }
  90.         
  91.         public List<string> GetTransactionHistory()
  92.         {
  93.             lock (_historyLock)
  94.             {
  95.                 return new List<string>(_transactionHistory);
  96.             }
  97.         }
  98.     }
  99.    
  100.     static void Main()
  101.     {
  102.         // 测试粗粒度锁的性能
  103.         var coarseAccount = new CoarseGrainedBankAccount();
  104.         var coarseStopwatch = System.Diagnostics.Stopwatch.StartNew();
  105.         
  106.         Parallel.For(0, 10000, i =>
  107.         {
  108.             if (i % 2 == 0)
  109.             {
  110.                 coarseAccount.Deposit(100);
  111.             }
  112.             else
  113.             {
  114.                 coarseAccount.Withdraw(50);
  115.             }
  116.         });
  117.         
  118.         coarseStopwatch.Stop();
  119.         Console.WriteLine($"粗粒度锁耗时: {coarseStopwatch.ElapsedMilliseconds} 毫秒");
  120.         Console.WriteLine($"最终余额: {coarseAccount.GetBalance()}");
  121.         
  122.         // 测试细粒度锁的性能
  123.         var fineAccount = new FineGrainedBankAccount();
  124.         var fineStopwatch = System.Diagnostics.Stopwatch.StartNew();
  125.         
  126.         Parallel.For(0, 10000, i =>
  127.         {
  128.             if (i % 2 == 0)
  129.             {
  130.                 fineAccount.Deposit(100);
  131.             }
  132.             else
  133.             {
  134.                 fineAccount.Withdraw(50);
  135.             }
  136.         });
  137.         
  138.         fineStopwatch.Stop();
  139.         Console.WriteLine($"细粒度锁耗时: {fineStopwatch.ElapsedMilliseconds} 毫秒");
  140.         Console.WriteLine($"最终余额: {fineAccount.GetBalance()}");
  141.         
  142.         Console.WriteLine($"性能提升: {(double)coarseStopwatch.ElapsedMilliseconds / fineStopwatch.ElapsedMilliseconds:F2}x");
  143.     }
  144. }
复制代码

7.3 使用不可变类型

不可变对象一旦创建就不能被修改,因此在多线程环境中使用不可变类型可以避免同步问题。
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Immutable;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. class ImmutableExample
  7. {
  8.     // 可变类型示例
  9.     class MutablePerson
  10.     {
  11.         public string Name { get; set; }
  12.         public int Age { get; set; }
  13.         
  14.         public MutablePerson(string name, int age)
  15.         {
  16.             Name = name;
  17.             Age = age;
  18.         }
  19.     }
  20.    
  21.     // 不可变类型示例
  22.     class ImmutablePerson
  23.     {
  24.         public string Name { get; }
  25.         public int Age { get; }
  26.         
  27.         public ImmutablePerson(string name, int age)
  28.         {
  29.             Name = name;
  30.             Age = age;
  31.         }
  32.         
  33.         // 返回一个新的不可变对象,而不是修改当前对象
  34.         public ImmutablePerson WithName(string name)
  35.         {
  36.             return new ImmutablePerson(name, Age);
  37.         }
  38.         
  39.         public ImmutablePerson WithAge(int age)
  40.         {
  41.             return new ImmutablePerson(Name, age);
  42.         }
  43.     }
  44.    
  45.     static void Main()
  46.     {
  47.         // 使用可变类型的线程安全问题
  48.         Console.WriteLine("可变类型示例:");
  49.         var mutablePerson = new MutablePerson("Alice", 30);
  50.         var mutableResults = new ConcurrentBag<string>();
  51.         
  52.         Parallel.For(0, 10000, i =>
  53.         {
  54.             // 读取和修改可变对象
  55.             string name = mutablePerson.Name;
  56.             int age = mutablePerson.Age;
  57.             
  58.             // 模拟一些处理
  59.             Thread.Sleep(1);
  60.             
  61.             // 更新对象(可能导致竞争条件)
  62.             mutablePerson.Name = $"{name}_{i}";
  63.             mutablePerson.Age = age + 1;
  64.             
  65.             if (i % 1000 == 0)
  66.             {
  67.                 mutableResults.Add($"迭代 {i}: Name={mutablePerson.Name}, Age={mutablePerson.Age}");
  68.             }
  69.         });
  70.         
  71.         Console.WriteLine($"最终结果: Name={mutablePerson.Name}, Age={mutablePerson.Age}");
  72.         
  73.         // 使用不可变类型的线程安全示例
  74.         Console.WriteLine("\n不可变类型示例:");
  75.         var immutablePerson = new ImmutablePerson("Bob", 30);
  76.         var immutableResults = new ConcurrentBag<string>();
  77.         
  78.         Parallel.For(0, 10000, i =>
  79.         {
  80.             // 读取不可变对象
  81.             string name = immutablePerson.Name;
  82.             int age = immutablePerson.Age;
  83.             
  84.             // 模拟一些处理
  85.             Thread.Sleep(1);
  86.             
  87.             // 创建新的不可变对象,而不是修改现有对象
  88.             immutablePerson = immutablePerson.WithName($"{name}_{i}").WithAge(age + 1);
  89.             
  90.             if (i % 1000 == 0)
  91.             {
  92.                 immutableResults.Add($"迭代 {i}: Name={immutablePerson.Name}, Age={immutablePerson.Age}");
  93.             }
  94.         });
  95.         
  96.         Console.WriteLine($"最终结果: Name={immutablePerson.Name}, Age={immutablePerson.Age}");
  97.         
  98.         // 使用.NET的不可变集合
  99.         Console.WriteLine("\n不可变集合示例:");
  100.         var immutableList = ImmutableList<int>.Empty;
  101.         var immutableListResults = new ConcurrentBag<string>();
  102.         
  103.         Parallel.For(0, 10000, i =>
  104.         {
  105.             // 创建新的不可变集合,而不是修改现有集合
  106.             immutableList = immutableList.Add(i);
  107.             
  108.             if (i % 1000 == 0)
  109.             {
  110.                 immutableListResults.Add($"迭代 {i}: 集合大小={immutableList.Count}");
  111.             }
  112.         });
  113.         
  114.         Console.WriteLine($"最终集合大小: {immutableList.Count}");
  115.     }
  116. }
复制代码

7.4 避免不必要的线程同步

线程同步会带来性能开销,因此应尽量避免不必要的同步。
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. class UnnecessarySynchronizationExample
  6. {
  7.     // 不必要的同步示例
  8.     class UnnecessarySyncCounter
  9.     {
  10.         private readonly object _lock = new object();
  11.         private int _count;
  12.         
  13.         public void Increment()
  14.         {
  15.             // 每个线程操作自己的局部变量,不需要同步
  16.             int localCount = 0;
  17.             for (int i = 0; i < 1000; i++)
  18.             {
  19.                 localCount++;
  20.             }
  21.             
  22.             // 只在最后需要更新共享状态时才同步
  23.             lock (_lock)
  24.             {
  25.                 _count += localCount;
  26.             }
  27.         }
  28.         
  29.         public int GetCount()
  30.         {
  31.             lock (_lock)
  32.             {
  33.                 return _count;
  34.             }
  35.         }
  36.     }
  37.    
  38.     // 使用线程局部存储避免同步
  39.     class ThreadLocalCounter
  40.     {
  41.         private int _count;
  42.         
  43.         // 每个线程有自己的计数器实例
  44.         private readonly ThreadLocal<int> _threadLocalCount =
  45.             new ThreadLocal<int>(() => 0);
  46.         
  47.         public void Increment()
  48.         {
  49.             // 使用线程局部变量,无需同步
  50.             for (int i = 0; i < 1000; i++)
  51.             {
  52.                 _threadLocalCount.Value++;
  53.             }
  54.         }
  55.         
  56.         public int GetCount()
  57.         {
  58.             // 汇总所有线程的计数
  59.             // 在实际应用中,可能需要更复杂的同步机制来确保一致性
  60.             return _count + _threadLocalCount.Value;
  61.         }
  62.     }
  63.    
  64.     // 使用并发集合避免同步
  65.     class ConcurrentCollectionCounter
  66.     {
  67.         private readonly ConcurrentBag<int> _counts = new ConcurrentBag<int>();
  68.         
  69.         public void Increment()
  70.         {
  71.             // 每个线程操作自己的局部变量
  72.             int localCount = 0;
  73.             for (int i = 0; i < 1000; i++)
  74.             {
  75.                 localCount++;
  76.             }
  77.             
  78.             // 使用线程安全的集合添加结果
  79.             _counts.Add(localCount);
  80.         }
  81.         
  82.         public int GetCount()
  83.         {
  84.             // 计算总和
  85.             int total = 0;
  86.             foreach (int count in _counts)
  87.             {
  88.                 total += count;
  89.             }
  90.             return total;
  91.         }
  92.     }
  93.    
  94.     static void Main()
  95.     {
  96.         // 测试不必要的同步
  97.         var unnecessarySync = new UnnecessarySyncCounter();
  98.         var unnecessarySyncStopwatch = System.Diagnostics.Stopwatch.StartNew();
  99.         
  100.         Parallel.For(0, 10000, i =>
  101.         {
  102.             unnecessarySync.Increment();
  103.         });
  104.         
  105.         unnecessarySyncStopwatch.Stop();
  106.         Console.WriteLine($"不必要的同步耗时: {unnecessarySyncStopwatch.ElapsedMilliseconds} 毫秒");
  107.         Console.WriteLine($"计数结果: {unnecessarySync.GetCount()}");
  108.         
  109.         // 测试线程局部存储
  110.         var threadLocalCounter = new ThreadLocalCounter();
  111.         var threadLocalStopwatch = System.Diagnostics.Stopwatch.StartNew();
  112.         
  113.         Parallel.For(0, 10000, i =>
  114.         {
  115.             threadLocalCounter.Increment();
  116.         });
  117.         
  118.         threadLocalStopwatch.Stop();
  119.         Console.WriteLine($"线程局部存储耗时: {threadLocalStopwatch.ElapsedMilliseconds} 毫秒");
  120.         Console.WriteLine($"计数结果: {threadLocalCounter.GetCount()}");
  121.         
  122.         // 测试并发集合
  123.         var concurrentCounter = new ConcurrentCollectionCounter();
  124.         var concurrentStopwatch = System.Diagnostics.Stopwatch.StartNew();
  125.         
  126.         Parallel.For(0, 10000, i =>
  127.         {
  128.             concurrentCounter.Increment();
  129.         });
  130.         
  131.         concurrentStopwatch.Stop();
  132.         Console.WriteLine($"并发集合耗时: {concurrentStopwatch.ElapsedMilliseconds} 毫秒");
  133.         Console.WriteLine($"计数结果: {concurrentCounter.GetCount()}");
  134.     }
  135. }
复制代码

7.5 使用CancellationToken取消长时间运行的操作

在多线程编程中,能够取消长时间运行的操作是一项重要功能。
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. class CancellationExample
  5. {
  6.     static void Main()
  7.     {
  8.         // 创建CancellationTokenSource
  9.         using (var cts = new CancellationTokenSource())
  10.         {
  11.             // 注册回调,在取消时执行
  12.             cts.Token.Register(() =>
  13.             {
  14.                 Console.WriteLine("操作已被取消");
  15.             });
  16.             
  17.             // 启动一个可取消的任务
  18.             Task longRunningTask = Task.Run(() => LongRunningOperation(cts.Token), cts.Token);
  19.             
  20.             Console.WriteLine("按C键取消操作,按其他键等待操作完成...");
  21.             
  22.             // 等待用户输入
  23.             if (Console.ReadKey().Key == ConsoleKey.C)
  24.             {
  25.                 // 取消操作
  26.                 cts.Cancel();
  27.             }
  28.             
  29.             try
  30.             {
  31.                 // 等待任务完成
  32.                 longRunningTask.Wait();
  33.             }
  34.             catch (AggregateException ex)
  35.             {
  36.                 foreach (var innerEx in ex.InnerExceptions)
  37.                 {
  38.                     if (innerEx is TaskCanceledException)
  39.                     {
  40.                         Console.WriteLine("任务被成功取消");
  41.                     }
  42.                     else
  43.                     {
  44.                         Console.WriteLine($"任务出错: {innerEx.Message}");
  45.                     }
  46.                 }
  47.             }
  48.         }
  49.         
  50.         Console.WriteLine("主线程退出");
  51.     }
  52.    
  53.     static void LongRunningOperation(CancellationToken cancellationToken)
  54.     {
  55.         Console.WriteLine("长时间运行的操作开始");
  56.         
  57.         try
  58.         {
  59.             for (int i = 0; i < 100; i++)
  60.             {
  61.                 // 检查是否已请求取消
  62.                 if (cancellationToken.IsCancellationRequested)
  63.                 {
  64.                     // 抛出OperationCanceledException
  65.                     cancellationToken.ThrowIfCancellationRequested();
  66.                 }
  67.                
  68.                 Console.WriteLine($"处理中: {i + 1}/100");
  69.                 Thread.Sleep(100);
  70.             }
  71.             
  72.             Console.WriteLine("长时间运行的操作完成");
  73.         }
  74.         catch (OperationCanceledException)
  75.         {
  76.             // 清理资源
  77.             Console.WriteLine("清理资源...");
  78.             Thread.Sleep(500);
  79.             
  80.             // 重新抛出异常
  81.             throw;
  82.         }
  83.     }
  84. }
复制代码

8. 总结

本文详细探讨了C#中线程与进程的概念、区别以及多线程编程的应用。我们了解了.NET框架下的并发处理机制,包括同步原语、线程安全集合、并行编程等。通过丰富的代码示例,我们展示了如何在实际开发中应用这些技术来提升程序性能和用户体验。

多线程编程是一项复杂但强大的技术,正确使用它可以显著提高应用程序的性能和响应能力。然而,它也带来了许多挑战,如线程安全、死锁、竞争条件等。遵循最佳实践,如减少锁的粒度、使用不可变类型、避免不必要的同步等,可以帮助我们构建更健壮、更高效的多线程应用程序。

随着.NET框架的不断发展,新的并发编程模式和API不断涌现,如Task Parallel Library (TPL)、Parallel LINQ (PLINQ)、async/await模式等,这些技术使得并发编程变得更加简单和直观。作为C#开发者,掌握这些技术并深入理解其背后的原理,将有助于我们构建更加高效、可靠的应用程序。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则