当前位置: 首页 > article >正文

C#系列-多线程(4)

 C#中,多线程编程主要涉及使用System.Threading命名空间下的类和接口来创建和管理线程。以下是一些C#多线程编程的基本用法和示例:

1. 使用Thread类创建线程

csharp代码

using System;

using System.Threading;

class Program

{

static void Main()

{

// 创建一个新的线程

Thread newThread = new Thread(new ThreadStart(ThreadFunction));

// 启动线程

newThread.Start();

// 等待线程完成

newThread.Join();

Console.WriteLine("Thread completed.");

}

static void ThreadFunction()

{

Console.WriteLine("Hello from a new thread!");

}

}

2. 使用TaskTask<T>类进行异步编程

Task类提供了基于任务的异步编程模型,它是推荐的方式来进行多线程编程,因为它提供了更好的控制和简洁的语法。

csharp代码

using System;

using System.Threading.Tasks;

class Program

{

static async Task Main()

{

Console.WriteLine("Starting a task...");

// 启动一个任务

Task task = Task.Run(() =>

{

Console.WriteLine("Hello from a task!");

});

// 等待任务完成

await task;

Console.WriteLine("Task completed.");

}

}

3. 使用Parallel类进行并行编程

Parallel类提供了并行执行循环和操作的功能。

csharp代码

using System;

using System.Threading.Tasks;

class Program

{

static void Main()

{

// 使用Parallel.For并行执行循环

Parallel.For(0, 10, i =>

{

Console.WriteLine($"Processing {i} on thread {Thread.CurrentThread.ManagedThreadId}");

});

}

}

4. 使用asyncawait关键字进行异步编程

asyncawait关键字使得异步编程更加简单和直观。

csharp代码

using System;

using System.Threading.Tasks;

class Program

{

static async Task Main()

{

Console.WriteLine("Starting an asynchronous operation...");

// 调用一个异步方法

int result = await PerformAsyncOperation();

Console.WriteLine($"Operation completed with result: {result}");

}

static async Task<int> PerformAsyncOperation()

{

// 模拟一个异步操作

await Task.Delay(1000);

return 42; // 返回结果

}

}

5. 使用ThreadPool

线程池(ThreadPool)是.NET Framework提供的一个线程管理机制,它允许你请求一个线程来执行一些任务,而不需要自己创建和管理线程。

csharp代码

using System;

using System.Threading;

class Program

{

static void Main()

{

// 将任务排入线程池队列

ThreadPool.QueueUserWorkItem(o =>

{

Console.WriteLine("Hello from the thread pool!");

});

Console.WriteLine("Task queued to the thread pool.");

}

}

6. 使用CancellationToken进行取消操作

在多线程编程中,可能需要取消正在进行的长时间运行的操作。CancellationTokenCancellationTokenSource类提供了取消操作的功能。

csharp代码

using System;

using System.Threading;

using System.Threading.Tasks;

class Program

{

static void Main()

{

// 创建一个取消令牌源

CancellationTokenSource cts = new CancellationTokenSource();

// 启动一个可取消的任务

Task task = Task.Run(() => DoWork(cts.Token), cts.Token);

// 在一段时间后取消任务

Thread.Sleep(2000);

cts.Cancel();

}

static void DoWork(CancellationToken token)

{

for (int i = 0; i < 10; i++)

{

token.ThrowIfCancellationRequested();

// 模拟工作

Thread.Sleep(500);

Console.WriteLine($"Working... {i}");

}

}

}

在以上示例中,我们展示了如何在C#中使用不同的类和方法来创建和管理多线程应用程序。选择哪种方法取决于你的具体需求,例如任务的性质(I/O密集型还是CPU密集型


http://www.kler.cn/news/234708.html

相关文章:

  • 极狐GitLab 使用阿里云作为 OmniAuth 身份验证 provider
  • springboot175图书管理系统
  • spring 常用的注入方式有哪些?spring 中的 bean 是线程安全的吗?spring 事务实现方式有哪些?
  • 酷开科技荣获“消费者服务之星”称号后的未来展望
  • 鸿蒙harmony--TypeScript函数详解
  • 【JAVA WEB】 百度热榜实现 新闻页面 Chrome 调试工具
  • django报错:Cannot use ImageField because Pillow is not installed
  • 设计模式-职责链模式Chain of Responsibility
  • rediss集群 三主三从集群模式
  • nginx添加lua模块
  • Learn LaTeX 015 - LaTex Typeset 抄录
  • 2.11 运算符
  • Stable Diffusion 模型下载:Samaritan 3d Cartoon(撒玛利亚人 3d 卡通)
  • 一键打造属于自己漏扫系统
  • [缓存] - Redis
  • ChatGPT高效提问—prompt常见用法
  • Netty应用(六) 之 异步 Channel
  • Flink从入门到实践(三):数据实时采集 - Flink MySQL CDC
  • C#在窗体正中输出文字以及输出文字的画刷使用
  • 单片机学习笔记---蜂鸣器播放提示音音乐(天空之城)
  • 物联网和工业4.0
  • 算法-3-基本的数据结构
  • QT+OSG/osgEarth编译之八十四:osgdb_osg+Qt编译(一套代码、一套框架,跨平台编译,版本:OSG-3.6.5插件库osgdb_osg)
  • RabbitMQ——构建高性能消息传递的应用
  • 彩虹系统7.0免授权+精美WAP端模板源码
  • 基于微信小程序的校园故障维修管理系统的研究与实现
  • 探索NLP中的N-grams:理解,应用与优化
  • 【Web】Spring rce CVE-2022-22965漏洞复现学习笔记
  • 《CSS 简易速速上手小册》第8章:CSS 性能优化和可访问性(2024 最新版)
  • 格式化dingo返回内容