【C# .NET】chapter 13 使用多任务改进性能和可扩展性
目录
一、物理内存和虚拟内存使用(Recorder 类)
二、 对比 string的“+”操作与stringbuilder 操作 的处理效率,内存消耗情况,
三、异步运行任务、三种启动任务方法、将上一任务方法处理结果作为参数传给下一任务方法
四、嵌套子任务
五、同步访问共享资源 Monitor.TryEnter、Monitor.Exit、 原子操作 Interlocked.Increment
六、理解async 和 await :改进控制台响应。 Main方法async Task
七、支持多任务的普通类型
八、异步流 返回类型IEnumerable
一、物理内存和虚拟内存使用(Recorder 类)
using System;
using System.Diagnostics;
using static System.Console;
using static System.Diagnostics.Process;namespace Packt.Shared
{public static class Recorder{static Stopwatch timer = new Stopwatch();static long bytesPhysicalBefore = 0;static long bytesVirtualBefore = 0;public static void Start(){// force two garbage collections to release memory that is no// longer referenced but has not been released yet// // 强制两次垃圾回收释放不再被引用但尚未释放的内存GC.Collect();GC.WaitForPendingFinalizers();//挂起当前线程,直到正在处理终结器队列的线程清空该队列。GC.Collect();//强制立即对所有代进行垃圾回收。//存储当前物理和虚拟内存使用 store the current physical and virtual memory usebytesPhysicalBefore = GetCurrentProcess().WorkingSet64;bytesVirtualBefore = GetCurrentProcess().VirtualMemorySize64;timer.Restart();}public static void Stop(){timer.Stop();long bytesPhysicalAfter = GetCurrentProcess().WorkingSet64;//计时停止时的 物理内存和虚拟内存使用long bytesVirtualAfter = GetCurrentProcess().VirtualMemorySize64;WriteLine("{0:N0} physical bytes used.",bytesPhysicalAfter - bytesPhysicalBefore);WriteLine("{0:N0} virtual bytes used.",bytesVirtualAfter - bytesVirtualBefore);WriteLine("{0} time span ellapsed.", timer.Elapsed);WriteLine("{0:N0} total milliseconds ellapsed.",timer.ElapsedMilliseconds);//获取当前实例测量的总运行时间,以毫秒为单位。}}
}
二、 对比 string的“+”操作与stringbuilder 操作 的处理效率,内存消耗情况,
using System;
using System.Linq;
using Packt.Shared;
using static System.Console;namespace MonitoringApp
{class Program{static void Main(string[] args){/*WriteLine("Processing. Please wait...");Recorder.Start();// simulate a process that requires some memory resources...int[] largeArrayOfInts = Enumerable.Range(1, 10_000).ToArray();// ...and takes some time to completeSystem.Threading.Thread.Sleep(new Random().Next(5, 10) * 1000);Recorder.Stop();*/int[] numbers = Enumerable.Range(1, 50_000).ToArray();//生成指定范围内的整数序列。WriteLine("Using string with +");Recorder.Start();string s = "";for (int i = 0; i < numbers.Length; i++){s += numbers[i] + ", ";}Recorder.Stop();/*Using string with +35,196,928 physical bytes used.6,291,456 virtual bytes used.00:00:04.0648349 time span ellapsed.4,064 total milliseconds ellapsed.Using StringBuilder0 physical bytes used.0 virtual bytes used.00:00:00.0018665 time span ellapsed.1 total milliseconds ellapsed.*/WriteLine("Using StringBuilder");Recorder.Start();var builder = new System.Text.StringBuilder();for (int i = 0; i < numbers.Length; i++){builder.Append(numbers[i]); builder.Append(", ");}Recorder.Stop();ReadLine();}}
}
三、异步运行任务、三种启动任务方法、将上一任务方法处理结果作为参数传给下一任务方法
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using static System.Console;namespace WorkingWithTasks
{class Program{static void MethodA(){WriteLine("Starting Method A...");Thread.Sleep(3000); // simulate three seconds of work WriteLine("Finished Method A.");}static void MethodB(){WriteLine("Starting Method B...");Thread.Sleep(2000); // simulate two seconds of work WriteLine("Finished Method B.");}static void MethodC(){WriteLine("Starting Method C...");Thread.Sleep(1000); // simulate one second of work WriteLine("Finished Method C.");}static decimal CallWebService(){WriteLine("Starting call to web service...");Thread.Sleep((new Random()).Next(2000, 4000));WriteLine("Finished call to web service.");return 89.99M;}static string CallStoredProcedure(decimal amount){WriteLine("Starting call to stored procedure...");Thread.Sleep((new Random()).Next(2000, 4000));WriteLine("Finished call to stored procedure.");return $"12 products cost more than {amount:C}.";}static void Main(string[] args){var timer = Stopwatch.StartNew();// WriteLine("Running methods synchronously on one thread.");// MethodA();// MethodB();// MethodC();/* //开启任务的三种方法WriteLine("Running methods asynchronously on multiple threads.");Task taskA = new Task(MethodA);taskA.Start();Task taskB = Task.Factory.StartNew(MethodB);Task taskC = Task.Run(new Action(MethodC));Task[] tasks = { taskA, taskB, taskC };Task.WaitAll(tasks);*/WriteLine("Passing the result of one task as an input into another.");//将CallWebService的结果作为输入传给CallStoredProcedure任务var taskCallWebServiceAndThenStoredProcedure =Task.Factory.StartNew(CallWebService).ContinueWith(previousTask =>CallStoredProcedure(previousTask.Result));WriteLine($"Result: {taskCallWebServiceAndThenStoredProcedure.Result}");WriteLine($"{timer.ElapsedMilliseconds:#,##0}ms elapsed.");ReadLine();}}
}
四、嵌套子任务
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using static System.Console;namespace NestedAndChildTasks
{class Program{static void OuterMethod(){WriteLine("Outer method starting...");var inner = Task.Factory.StartNew(InnerMethod,TaskCreationOptions.AttachedToParent);//开启嵌套任务WriteLine("Outer method finished.");}static void InnerMethod()//嵌套子任务方法{WriteLine("Inner method starting...");Thread.Sleep(2000);WriteLine("Inner method finished.");}static void Main(string[] args){var outer = Task.Factory.StartNew(OuterMethod);outer.Wait();//等待嵌套子任务完成后才继续WriteLine("Console app is stopping.");}}
}
五、同步访问共享资源 Monitor.TryEnter、Monitor.Exit、 原子操作 Interlocked.Increment
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using static System.Console;namespace SynchronizingResourceAccess
{class Program{static Random r = new Random();static string Message; // 一个共享资源static int Counter; //另一共享资源static object conch = new object();//互斥锁static void MethodA(){try{ //在指定的时间内尝试获取指定对象的独占锁。if (Monitor.TryEnter(conch, TimeSpan.FromSeconds(15))){for (int i = 0; i < 5; i++){Thread.Sleep(r.Next(2000));Message += "A";Interlocked.Increment(ref Counter);//递增指定变量并将结果存储为原子操作。Write(".");}}else{WriteLine("Method A failed to enter a monitor lock.");}}finally{Monitor.Exit(conch);//释放指定对象上的独占锁。}}static void MethodB(){try{if (Monitor.TryEnter(conch, TimeSpan.FromSeconds(15))){for (int i = 0; i < 5; i++){Thread.Sleep(r.Next(2000));Message += "B";Interlocked.Increment(ref Counter);Write(".");}}else{WriteLine("Method B failed to enter a monitor lock.");}}finally{Monitor.Exit(conch);}}/*Please wait for the tasks to complete...........Results: AAAAABBBBB.9,083 elapsed milliseconds.10 string modifications.*/static void Main(string[] args){WriteLine("Please wait for the tasks to complete.");Stopwatch watch = Stopwatch.StartNew();Task a = Task.Factory.StartNew(MethodA);Task b = Task.Factory.StartNew(MethodB);Task.WaitAll(new Task[] { a, b });WriteLine();WriteLine($"Results: {Message}.");WriteLine($"{watch.ElapsedMilliseconds:#,##0} elapsed milliseconds.");WriteLine($"{Counter} string modifications.");ReadLine();}}
}
六、理解async 和 await :改进控制台响应。 Main方法async Task
从C#6开始可以在try\catch块中使用await
using System;
using System.Net.Http;
using System.Threading.Tasks;
using static System.Console;namespace AsyncConsole
{class Program{static async Task Main(string[] args){var client = new HttpClient();HttpResponseMessage response =await client.GetAsync("http://www.apple.com/");WriteLine("Apple's home page has {0:N0} bytes.",response.Content.Headers.ContentLength);}}
}
七、支持多任务的普通类型
八、异步流 返回类型IEnumerable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using static System.Console;namespace AsyncEnumerable
{class Program{async static IAsyncEnumerable<int> GetNumbers(){var r = new Random();// simulate workawait Task.Run(() => Task.Delay(r.Next(1500, 3000)));yield return r.Next(0, 1001);await Task.Run(() => Task.Delay(r.Next(1500, 3000)));yield return r.Next(0, 1001);await Task.Run(() => Task.Delay(r.Next(1500, 3000)));yield return r.Next(0, 1001);}static async Task Main(string[] args){await foreach (int number in GetNumbers()){WriteLine($"Number: {number}");}}}
}
相关文章:

【C# .NET】chapter 13 使用多任务改进性能和可扩展性
目录 一、物理内存和虚拟内存使用(Recorder 类) 二、 对比 string的“”操作与stringbuilder 操作 的处理效率,内存消耗情况, 三、异步运行任务、三种启动任务方法、将上一任务方法处理结果作为参数传给下一任务方法 四、嵌套…...

CA(证书颁发机构)
CA 根证书路径/csk-rootca/csk-ca.pem; ~ 签发数字证书,颁发者信息:(仅包含如下信息) C CN ST China L BeiJing O skills OU Operations Departments CN CSK Global Root CA 1.修改证书的路径以及相关配置 vi /etc/pki/tls/op…...

辛弃疾最有代表性的十首词
辛弃疾的词,风格多样,题材广阔,几乎涉及到生活中的各个方面,从爱国情怀到日常生活,甚至连戒酒这种事都能写入词中。辛弃疾也是两宋词人中,存词最多的作家之一,现存的六百多首作品。 辛弃疾的词…...

MC9S12G128开发板—实现按键发送CAN报文指示小车移动功能
实验环境:MC9S12G128开发板 基本功能:控制开发板上的按键,模拟车辆移动的上下左右四个方位,通过can通信告诉上位机界面,车辆轨迹的移动方位。 1. 1939报文发送的示例代码 MC9S12G128开发板1939协议发送can报文数据的…...

尚融宝22-提交借款申请
目录 一、需求介绍 二、图片上传 (一)前端页面 (二)实现图片上传 三、数据字典展示 (一)后端 (二)前端 四、表单信息提交 (一)后端 1、VO对象&…...

机器学习在生态、环境经济学中的实践技术应用及论文写作
近年来,人工智能领域已经取得突破性进展,对经济社会各个领域都产生了重大影响,结合了统计学、数据科学和计算机科学的机器学习是人工智能的主流方向之一,目前也在飞快的融入计量经济学研究。表面上机器学习通常使用大数据…...

Android硬件通信之 WIFI通信
一,简介 1.1 随着网络的普及和通信技术的发展,网络的传输速度也越来越快,wifi技术也还成为手机设备最基本的配置。我们可以通过wifi实现手机与手机之前的信息传输,当然也可以与任意一台有wifi模块的其它设备传输。 1.2 wifi与蓝…...

面试官:“请描述一下Android系统的启动流程”
作者:OpenGL 前言 什么是Android启动流程呢?其实指的就是我们Android系统从按下电源到显示界面的整个过程。 当我们把手机充好电,按下电源,手机会弹出相应启动界面,在等了一段时间之后,会弹出我们熟悉的主…...
k8s delete node 后 重启kubelet会自己加入到集群 ?
原因 当执行kubectl delete node命令时,Kubernetes API服务器会收到该节点的删除请求,并将其从集群中删除。此时,kubelet服务在该节点上仍然在运行,但已经不再与集群通信。 当您重启kubelet服务时,它会重新向API服务…...

REXROTH液压方向阀安装须知
安装规程 阀安装到系统之前,应该对照订货型号比较其型号说明。 确认阀的连接表面和底板无水分,没有油。 - 清洁: ‧ 安装元件时,确认工业阀和周围干净 ‧ 油箱须密闭,以防止外部污染 ‧ 安装之前&…...
【数据结构实验】哈夫曼树
【数据结构实验】哈夫曼树 简介: 为一个信息收发站编写一个哈夫曼码的编/译码系统。文末贴出了源代码。 需求分析 完整的系统需要具备完整的功能,包含初始化、编码、译码、印代码文件和印哈夫曼树,因此需要进行相应的文件操作进行配合。哈…...

浏览器不好用?插件来帮忙
一、目的 浏览器本身具备的功能并不完善,不同的用户可以为自己浏览器增加想要功能,使得浏览器更能符合自己的需求,提高浏览器使用的舒适度 二、推荐插件 AdblockPlus LastPass(密码记录,全平台通用) Dar…...

Qt Quick - 容器控件综述
Qt Quick - 容器控件综述 一、概述二、ApplicationWindow Control三、Frame Control四、GroupBox Control五、Page Control六、Pane Control七、ScrollView Control八、StackView Control九、SwipeView Control十、TabBarControl十一、ToolBar控件 一、概述 Qt Quick Controls…...
面试题30天打卡-day06
1、什么是反射机制?说说反射机制的优缺点、应用场景? 反射机制:Java的反射机制是在运行状态,对于任意一个类,都能够动态的获得这个类的属性和方法;对于一个对象,都能动态的调用它当中的方法和属…...

Spring Boot的基础使用和< artifactId>spring-boot-maven-plugin</ artifactId>爆红的处理
Spring Boot的基础使用和< artifactId>spring-boot-maven-plugin</ artifactId>爆红的处理 Spring Boot概述 微服务概述 微服务Microservices是一种软件架构风格,他是以专注于单一责任与功能的小型功能区块Small Building Blocks 为基础,…...

项目管理中的必不可少的强大工具有哪些?
在项目管理中,我们总是想寻求一套功能强大的工具,来满足我们多样化的需求。但往往事与愿违,这样强大的工具总是费用高,操作复杂,需安装多个插件。下面,我就给大家推荐一款项目管理软件 ~Zoho Projects&…...

嵌入式学习笔记——SPI通信的应用
SPI通信的应用 前言屏幕分类1.3OLED概述驱动芯片框图原理图通信时序显示的方式页地址、列地址初始化指令 程序设计初始化代码初始化写数据与写命令清屏函数 初始化代码字符显示函数 总结 前言 上一篇中介绍了STM32的SPI通信,并根据框图和寄存器进行了SPI通信的初始…...
.Net下企业应用系统架构构建心得
在开始架构设计之前,需要了解一下架构是什么,按照IEEE标准的定义是: Architecture 是一个系统的基本组织,它蕴含于系统的组件中、组件之间的相互关系中、组件与环境的相互关系中、以及呈现于其设计和演进的原则中。 (The embodied…...
【社区图书馆】关于Mybatis原理学习的读后感
1、为什么会看原理书籍 Mybatis是我们Java后端开发中的主流ORM框架,基本都会在工作中用到。所以,是既熟悉,又陌生。熟悉是因为一直都在使用,而陌生则是对于其内部原理还不够深入。刚好近期的工作中,又遇到了一个需求&a…...

C++ Primer阅读笔记--表达式和运算符的使用
1--左值和右值 C 的表达式有右值(rvalue, are-value)和左值(lvalue, ell-value)两个形式;当一个对象被用作右值时,使用的是对象的值(内容);当对象被用作左值时࿰…...

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明
LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造,完美适配AGV和无人叉车。同时,集成以太网与语音合成技术,为各类高级系统(如MES、调度系统、库位管理、立库等)提供高效便捷的语音交互体验。 L…...
多场景 OkHttpClient 管理器 - Android 网络通信解决方案
下面是一个完整的 Android 实现,展示如何创建和管理多个 OkHttpClient 实例,分别用于长连接、普通 HTTP 请求和文件下载场景。 <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas…...
【python异步多线程】异步多线程爬虫代码示例
claude生成的python多线程、异步代码示例,模拟20个网页的爬取,每个网页假设要0.5-2秒完成。 代码 Python多线程爬虫教程 核心概念 多线程:允许程序同时执行多个任务,提高IO密集型任务(如网络请求)的效率…...

基于 TAPD 进行项目管理
起因 自己写了个小工具,仓库用的Github。之前在用markdown进行需求管理,现在随着功能的增加,感觉有点难以管理了,所以用TAPD这个工具进行需求、Bug管理。 操作流程 注册 TAPD,需要提供一个企业名新建一个项目&#…...

解读《网络安全法》最新修订,把握网络安全新趋势
《网络安全法》自2017年施行以来,在维护网络空间安全方面发挥了重要作用。但随着网络环境的日益复杂,网络攻击、数据泄露等事件频发,现行法律已难以完全适应新的风险挑战。 2025年3月28日,国家网信办会同相关部门起草了《网络安全…...

Chromium 136 编译指南 Windows篇:depot_tools 配置与源码获取(二)
引言 工欲善其事,必先利其器。在完成了 Visual Studio 2022 和 Windows SDK 的安装后,我们即将接触到 Chromium 开发生态中最核心的工具——depot_tools。这个由 Google 精心打造的工具集,就像是连接开发者与 Chromium 庞大代码库的智能桥梁…...

小智AI+MCP
什么是小智AI和MCP 如果还不清楚的先看往期文章 手搓小智AI聊天机器人 MCP 深度解析:AI 的USB接口 如何使用小智MCP 1.刷支持mcp的小智固件 2.下载官方MCP的示例代码 Github:https://github.com/78/mcp-calculator 安这个步骤执行 其中MCP_ENDPOI…...
Django RBAC项目后端实战 - 03 DRF权限控制实现
项目背景 在上一篇文章中,我们完成了JWT认证系统的集成。本篇文章将实现基于Redis的RBAC权限控制系统,为系统提供细粒度的权限控制。 开发目标 实现基于Redis的权限缓存机制开发DRF权限控制类实现权限管理API配置权限白名单 前置配置 在开始开发权限…...
MeanFlow:何凯明新作,单步去噪图像生成新SOTA
1.简介 这篇文章介绍了一种名为MeanFlow的新型生成模型框架,旨在通过单步生成过程高效地将先验分布转换为数据分布。文章的核心创新在于引入了平均速度的概念,这一概念的引入使得模型能够通过单次函数评估完成从先验分布到数据分布的转换,显…...
c++算法学习3——深度优先搜索
一、深度优先搜索的核心概念 DFS算法是一种通过递归或栈实现的"一条路走到底"的搜索策略,其核心思想是: 深度优先:从起点出发,选择一个方向探索到底,直到无路可走 回溯机制:遇到死路时返回最近…...