c#使用多线程的几种方式示例详解

c#
1108
2023/7/25 14:39:03
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

C#中使用多线程的几种方式有以下几种:

  1. 使用Thread类:Thread类是C#中最基本的多线程类,可以使用它创建和控制线程。下面是一个使用Thread类创建并启动线程的示例:
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread = new Thread(DoWork);
thread.Start();
// 主线程继续执行其他操作
Console.WriteLine("Main thread is working...");
// 等待子线程结束
thread.Join();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("Child thread is working...");
// 模拟耗时操作
Thread.Sleep(2000);
Console.WriteLine("Child thread completed.");
}
}
  1. 使用ThreadPool类:ThreadPool类是C#中用于管理线程池的类,它可以自动分配和管理线程。下面是一个使用ThreadPool类执行异步操作的示例:
using System;
using System.Threading;
class Program
{
static void Main()
{
ThreadPool.QueueUserWorkItem(DoWork);
// 主线程继续执行其他操作
Console.WriteLine("Main thread is working...");
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static void DoWork(object state)
{
Console.WriteLine("Child thread is working...");
// 模拟耗时操作
Thread.Sleep(2000);
Console.WriteLine("Child thread completed.");
}
}
  1. 使用Task类:Task类是C#中用于异步编程的类,它提供了更高级的多线程管理功能。下面是一个使用Task类执行异步操作的示例:
using System;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Task task = Task.Run(DoWork);
// 主线程继续执行其他操作
Console.WriteLine("Main thread is working...");
// 等待任务完成
task.Wait();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("Child thread is working...");
// 模拟耗时操作
Task.Delay(2000).Wait();
Console.WriteLine("Child thread completed.");
}
}

以上示例分别使用了Thread类、ThreadPool类和Task类创建和管理线程。根据实际需求和情况选择合适的方式来使用多线程。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C#中怎么处理日期和时间