C#编程实现多线程的几种方式
|
admin
2024年6月8日 18:35
本文热度 996
|
前言
多线程是C#中一个重要的概念,多线程指的是在同一进程中同时运行多个线程的机制。多线程适用于需要提高系统并发性、吞吐量和响应速度的场景,可以充分利用多核处理器和系统资源,提高应用程序的性能和效率。
多线程常用场景
什么是进程?
进程(Process)是计算机中的一个执行中的程序,它是对正在运行的程序的抽象。一个进程包括了程序的代码、数据、堆栈以及其他操作系统所需的资源。

什么是线程?
线程(Thread)是进程中的一个执行单元,一个进程可以包含多个线程,它们共享进程的资源,但拥有独立的执行流程。
使用 Thread 类
public static void ThreadMethod()
{
var newThread = new Thread(WorkerMethod);
newThread.Start();
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"ThreadMethod 飨叱炭脊ぷ鳎簕i}");
Thread.Sleep(100);
}
}
private static void WorkerMethod()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethod 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}

使用 ThreadPool 类
public static void ThreadPoolMethod()
{
ThreadPool.QueueUserWorkItem(o => WorkerMethod());
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"ThreadPoolMethod 主线程开始工作:{i}");
Thread.Sleep(100);
}
}
private static void WorkerMethod()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethod 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}

使用 Task 类
public static void TaskMethod()
{
Task.Run(() => WorkerMethod());
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"TaskMethod 主线程开始工作:{i}");
Task.Delay(100).Wait();
}
}
private static void WorkerMethod()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethod 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}

使用 Parallel 类
public static void ParallelMethod()
{
Parallel.Invoke(WorkerMethod, WorkerMethodOther1, WorkerMethodOther2);
}
private static void WorkerMethod()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethod 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}
private static void WorkerMethodOther1()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethodOther1 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}
private static void WorkerMethodOther2()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethodOther2 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}
该文章在 2024/6/8 18:36:37 编辑过