C#:多线程 简单示例

在C#中,多线程编程是一种提高应用程序性能和响应能力的方法。通过使用多线程,你可以同时执行多个任务,从而充分利用现代多核处理器的能力。C#提供了多种方法和工具来管理和操作线程。

以下是一些关键概念和示例代码,帮助你理解如何在C#中使用多线程:

  1. 使用 Thread 类

Thread 类是C#中最基本的线程类。你可以创建一个新的 Thread 对象,并为其指定一个要执行的方法。

cs 复制代码
using System;
using System.Threading;
 
class Program
{
    static void Main(string[] args)
    {
        Thread thread = new Thread(new ThreadStart(DoWork));
        thread.Start();
 
        // 等待线程完成
        thread.Join();
 
        Console.WriteLine("Main thread exiting.");
    }
 
    static void DoWork()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Thread working: " + i);
            Thread.Sleep(1000); // 模拟工作负载
        }
    }
}
  1. 使用 ParameterizedThreadStart

有时候你可能需要向线程传递参数,这时可以使用 ParameterizedThreadStart 委托

cs 复制代码
using System;
using System.Threading;
 
class Program
{
    static void Main(string[] args)
    {
        Thread thread = new Thread(new ParameterizedThreadStart(DoWorkWithParam));
        thread.Start("Hello from main thread");
 
        thread.Join();
 
        Console.WriteLine("Main thread exiting.");
    }
 
    static void DoWorkWithParam(object param)
    {
        string message = (string)param;
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Thread working with param: " + message + ", count: " + i);
            Thread.Sleep(1000); // 模拟工作负载
        }
    }
}
  1. 使用 ThreadPool

ThreadPool 提供了一种管理线程池的方法,这样可以避免手动创建和销毁线程带来的开销。

cs 复制代码
using System;
using System.Threading;
 
class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            ThreadPool.QueueUserWorkItem(DoWork);
        }
 
        // 等待一段时间,确保所有线程完成(在实际应用中,可以使用更复杂的同步机制)
        Thread.Sleep(5000);
 
        Console.WriteLine("Main thread exiting.");
    }
 
    static void DoWork(object state)
    {
        int index = (int)state;
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Thread pool working: " + index + ", count: " + i);
            Thread.Sleep(1000); // 模拟工作负载
        }
    }
}
  1. 使用 Task 和 Task Parallel Library (TPL)

Task 类和 Task Parallel Library (TPL) 提供了一种更高级、更易于使用的多线程编程模型。

cs 复制代码
using System;
using System.Threading.Tasks;
 
class Program
{
    static void Main(string[] args)
    {
        Task task1 = Task.Run(() => DoWork(1));
        Task task2 = Task.Run(() => DoWork(2));
 
        Task.WaitAll(task1, task2); // 等待所有任务完成
 
        Console.WriteLine("Main thread exiting.");
    }
 
    static void DoWork(int taskId)
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Task " + taskId + " working: " + i);
            Task.Delay(1000).Wait(); // 模拟工作负载
        }
    }
}
  1. 使用 async 和 await

async 和 await 关键字提供了一种基于任务的异步编程模式,可以简化异步编程的复杂性。

cs 复制代码
using System;
using System.Threading.Tasks;
 
class Program
{
    static async Task Main(string[] args)
    {
        await DoWorkAsync(1);
        await DoWorkAsync(2);
 
        Console.WriteLine("Main thread exiting.");
    }
 
    static async Task DoWorkAsync(int taskId)
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Task " + taskId + " working: " + i);
            await Task.Delay(1000); // 模拟工作负载
        }
    }
}

注意事项

线程安全:多线程编程中,确保对共享资源的访问是线程安全的非常重要。你可以使用锁(lock)、Monitor 类、Mutex、Semaphore、ReaderWriterLockSlim 等机制来实现线程同步。

死锁:避免多个线程相互等待对方释放资源,从而导致死锁。

性能开销:创建和销毁线程有一定的性能开销,因此尽量重用线程(例如使用线程池)。

异常处理:在多线程环境中,确保对异常进行适当的处理,避免未捕获的异常导致应用程序崩溃。

通过掌握这些概念和工具,你可以有效地在C#中进行多线程编程,从而充分利用多核处理器的优势,提高应用程序的性能和响应能力。

相关推荐
XYR1212126 小时前
C# 参数
c#
oMMh7 小时前
使用C# ASP.NET创建一个可以由服务端推送信息至客户端的WEB应用(2)
前端·c#·asp.net
Risehuxyc8 小时前
GrassRoot备份项目
c#
咩咩觉主8 小时前
c#数据结构 线性表篇 非常用线性集合总结
开发语言·数据结构·unity·c#·游戏引擎·程序框架
Kookoos9 小时前
ABP vNext + Dapr 实现云原生微服务治理
微服务·云原生·架构·c#·.net
火星papa10 小时前
C# 通过ConfigurationManager读写配置文件App.Config
c#·配置文件·app.config
bicijinlian10 小时前
.Net HttpClient 处理响应数据
c#·.net·httpclient·.net httpclient
编程乐趣11 小时前
一个.Net开源的关系管理系统
开源·c#·.net
E-iceblue13 小时前
C# 从PDF文档中提取图片
c#·.net·提取图片·pdf提取
rrokoko14 小时前
模拟太阳系(C#编写的maui跨平台项目源码)
c#·maui跨平台