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

【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 使用多任务改进性能和可扩展性

目录 一、物理内存和虚拟内存使用&#xff08;Recorder 类&#xff09; 二、 对比 string的“”操作与stringbuilder 操作 的处理效率&#xff0c;内存消耗情况&#xff0c; 三、异步运行任务、三种启动任务方法、将上一任务方法处理结果作为参数传给下一任务方法 四、嵌套…...

CA(证书颁发机构)

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

辛弃疾最有代表性的十首词

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

MC9S12G128开发板—实现按键发送CAN报文指示小车移动功能

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

尚融宝22-提交借款申请

目录 一、需求介绍 二、图片上传 &#xff08;一&#xff09;前端页面 &#xff08;二&#xff09;实现图片上传 三、数据字典展示 &#xff08;一&#xff09;后端 &#xff08;二&#xff09;前端 四、表单信息提交 &#xff08;一&#xff09;后端 1、VO对象&…...

机器学习在生态、环境经济学中的实践技术应用及论文写作

近年来&#xff0c;人工智能领域已经取得突破性进展&#xff0c;对经济社会各个领域都产生了重大影响&#xff0c;结合了统计学、数据科学和计算机科学的机器学习是人工智能的主流方向之一&#xff0c;目前也在飞快的融入计量经济学研究。表面上机器学习通常使用大数据&#xf…...

Android硬件通信之 WIFI通信

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

面试官:“请描述一下Android系统的启动流程”

作者&#xff1a;OpenGL 前言 什么是Android启动流程呢&#xff1f;其实指的就是我们Android系统从按下电源到显示界面的整个过程。 当我们把手机充好电&#xff0c;按下电源&#xff0c;手机会弹出相应启动界面&#xff0c;在等了一段时间之后&#xff0c;会弹出我们熟悉的主…...

k8s delete node 后 重启kubelet会自己加入到集群 ?

原因 当执行kubectl delete node命令时&#xff0c;Kubernetes API服务器会收到该节点的删除请求&#xff0c;并将其从集群中删除。此时&#xff0c;kubelet服务在该节点上仍然在运行&#xff0c;但已经不再与集群通信。 当您重启kubelet服务时&#xff0c;它会重新向API服务…...

REXROTH液压方向阀安装须知

安装规程 阀安装到系统之前&#xff0c;应该对照订货型号比较其型号说明。 确认阀的连接表面和底板无水分&#xff0c;没有油。 &#xff0d; 清洁&#xff1a; ‧ 安装元件时&#xff0c;确认工业阀和周围干净 ‧ 油箱须密闭&#xff0c;以防止外部污染 ‧ 安装之前&…...

【数据结构实验】哈夫曼树

【数据结构实验】哈夫曼树 简介&#xff1a; 为一个信息收发站编写一个哈夫曼码的编/译码系统。文末贴出了源代码。 需求分析 完整的系统需要具备完整的功能&#xff0c;包含初始化、编码、译码、印代码文件和印哈夫曼树&#xff0c;因此需要进行相应的文件操作进行配合。哈…...

浏览器不好用?插件来帮忙

一、目的 浏览器本身具备的功能并不完善&#xff0c;不同的用户可以为自己浏览器增加想要功能&#xff0c;使得浏览器更能符合自己的需求&#xff0c;提高浏览器使用的舒适度 二、推荐插件 AdblockPlus LastPass&#xff08;密码记录&#xff0c;全平台通用&#xff09; 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、什么是反射机制&#xff1f;说说反射机制的优缺点、应用场景&#xff1f; 反射机制&#xff1a;Java的反射机制是在运行状态&#xff0c;对于任意一个类&#xff0c;都能够动态的获得这个类的属性和方法&#xff1b;对于一个对象&#xff0c;都能动态的调用它当中的方法和属…...

Spring Boot的基础使用和< artifactId>spring-boot-maven-plugin</ artifactId>爆红的处理

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

项目管理中的必不可少的强大工具有哪些?

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

嵌入式学习笔记——SPI通信的应用

SPI通信的应用 前言屏幕分类1.3OLED概述驱动芯片框图原理图通信时序显示的方式页地址、列地址初始化指令 程序设计初始化代码初始化写数据与写命令清屏函数 初始化代码字符显示函数 总结 前言 上一篇中介绍了STM32的SPI通信&#xff0c;并根据框图和寄存器进行了SPI通信的初始…...

.Net下企业应用系统架构构建心得

在开始架构设计之前&#xff0c;需要了解一下架构是什么&#xff0c;按照IEEE标准的定义是&#xff1a; Architecture 是一个系统的基本组织&#xff0c;它蕴含于系统的组件中、组件之间的相互关系中、组件与环境的相互关系中、以及呈现于其设计和演进的原则中。 (The embodied…...

【社区图书馆】关于Mybatis原理学习的读后感

1、为什么会看原理书籍 Mybatis是我们Java后端开发中的主流ORM框架&#xff0c;基本都会在工作中用到。所以&#xff0c;是既熟悉&#xff0c;又陌生。熟悉是因为一直都在使用&#xff0c;而陌生则是对于其内部原理还不够深入。刚好近期的工作中&#xff0c;又遇到了一个需求&a…...

C++ Primer阅读笔记--表达式和运算符的使用

1--左值和右值 C 的表达式有右值&#xff08;rvalue, are-value&#xff09;和左值&#xff08;lvalue, ell-value&#xff09;两个形式&#xff1b;当一个对象被用作右值时&#xff0c;使用的是对象的值&#xff08;内容&#xff09;&#xff1b;当对象被用作左值时&#xff0…...

智慧医疗能源事业线深度画像分析(上)

引言 医疗行业作为现代社会的关键基础设施,其能源消耗与环境影响正日益受到关注。随着全球"双碳"目标的推进和可持续发展理念的深入,智慧医疗能源事业线应运而生,致力于通过创新技术与管理方案,重构医疗领域的能源使用模式。这一事业线融合了能源管理、可持续发…...

Docker 运行 Kafka 带 SASL 认证教程

Docker 运行 Kafka 带 SASL 认证教程 Docker 运行 Kafka 带 SASL 认证教程一、说明二、环境准备三、编写 Docker Compose 和 jaas文件docker-compose.yml代码说明&#xff1a;server_jaas.conf 四、启动服务五、验证服务六、连接kafka服务七、总结 Docker 运行 Kafka 带 SASL 认…...

dedecms 织梦自定义表单留言增加ajax验证码功能

增加ajax功能模块&#xff0c;用户不点击提交按钮&#xff0c;只要输入框失去焦点&#xff0c;就会提前提示验证码是否正确。 一&#xff0c;模板上增加验证码 <input name"vdcode"id"vdcode" placeholder"请输入验证码" type"text&quo…...

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...

【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具

第2章 虚拟机性能监控&#xff0c;故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令&#xff1a;jps [options] [hostid] 功能&#xff1a;本地虚拟机进程显示进程ID&#xff08;与ps相同&#xff09;&#xff0c;可同时显示主类&#x…...

全志A40i android7.1 调试信息打印串口由uart0改为uart3

一&#xff0c;概述 1. 目的 将调试信息打印串口由uart0改为uart3。 2. 版本信息 Uboot版本&#xff1a;2014.07&#xff1b; Kernel版本&#xff1a;Linux-3.10&#xff1b; 二&#xff0c;Uboot 1. sys_config.fex改动 使能uart3(TX:PH00 RX:PH01)&#xff0c;并让boo…...

Unity | AmplifyShaderEditor插件基础(第七集:平面波动shader)

目录 一、&#x1f44b;&#x1f3fb;前言 二、&#x1f608;sinx波动的基本原理 三、&#x1f608;波动起来 1.sinx节点介绍 2.vertexPosition 3.集成Vector3 a.节点Append b.连起来 4.波动起来 a.波动的原理 b.时间节点 c.sinx的处理 四、&#x1f30a;波动优化…...

论文阅读笔记——Muffin: Testing Deep Learning Libraries via Neural Architecture Fuzzing

Muffin 论文 现有方法 CRADLE 和 LEMON&#xff0c;依赖模型推理阶段输出进行差分测试&#xff0c;但在训练阶段是不可行的&#xff0c;因为训练阶段直到最后才有固定输出&#xff0c;中间过程是不断变化的。API 库覆盖低&#xff0c;因为各个 API 都是在各种具体场景下使用。…...

离线语音识别方案分析

随着人工智能技术的不断发展&#xff0c;语音识别技术也得到了广泛的应用&#xff0c;从智能家居到车载系统&#xff0c;语音识别正在改变我们与设备的交互方式。尤其是离线语音识别&#xff0c;由于其在没有网络连接的情况下仍然能提供稳定、准确的语音处理能力&#xff0c;广…...

Mysql故障排插与环境优化

前置知识点 最上层是一些客户端和连接服务&#xff0c;包含本 sock 通信和大多数jiyukehuduan/服务端工具实现的TCP/IP通信。主要完成一些简介处理、授权认证、及相关的安全方案等。在该层上引入了线程池的概念&#xff0c;为通过安全认证接入的客户端提供线程。同样在该层上可…...