【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)两个形式;当一个对象被用作右值时,使用的是对象的值(内容);当对象被用作左值时࿰…...

第19节 Node.js Express 框架
Express 是一个为Node.js设计的web开发框架,它基于nodejs平台。 Express 简介 Express是一个简洁而灵活的node.js Web应用框架, 提供了一系列强大特性帮助你创建各种Web应用,和丰富的HTTP工具。 使用Express可以快速地搭建一个完整功能的网站。 Expre…...

Flask RESTful 示例
目录 1. 环境准备2. 安装依赖3. 修改main.py4. 运行应用5. API使用示例获取所有任务获取单个任务创建新任务更新任务删除任务 中文乱码问题: 下面创建一个简单的Flask RESTful API示例。首先,我们需要创建环境,安装必要的依赖,然后…...
应用升级/灾备测试时使用guarantee 闪回点迅速回退
1.场景 应用要升级,当升级失败时,数据库回退到升级前. 要测试系统,测试完成后,数据库要回退到测试前。 相对于RMAN恢复需要很长时间, 数据库闪回只需要几分钟。 2.技术实现 数据库设置 2个db_recovery参数 创建guarantee闪回点,不需要开启数据库闪回。…...
React hook之useRef
React useRef 详解 useRef 是 React 提供的一个 Hook,用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途,下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...
leetcodeSQL解题:3564. 季节性销售分析
leetcodeSQL解题:3564. 季节性销售分析 题目: 表:sales ---------------------- | Column Name | Type | ---------------------- | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | -…...

ardupilot 开发环境eclipse 中import 缺少C++
目录 文章目录 目录摘要1.修复过程摘要 本节主要解决ardupilot 开发环境eclipse 中import 缺少C++,无法导入ardupilot代码,会引起查看不方便的问题。如下图所示 1.修复过程 0.安装ubuntu 软件中自带的eclipse 1.打开eclipse—Help—install new software 2.在 Work with中…...

零基础设计模式——行为型模式 - 责任链模式
第四部分:行为型模式 - 责任链模式 (Chain of Responsibility Pattern) 欢迎来到行为型模式的学习!行为型模式关注对象之间的职责分配、算法封装和对象间的交互。我们将学习的第一个行为型模式是责任链模式。 核心思想:使多个对象都有机会处…...
【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具
第2章 虚拟机性能监控,故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令:jps [options] [hostid] 功能:本地虚拟机进程显示进程ID(与ps相同),可同时显示主类&#x…...
重启Eureka集群中的节点,对已经注册的服务有什么影响
先看答案,如果正确地操作,重启Eureka集群中的节点,对已经注册的服务影响非常小,甚至可以做到无感知。 但如果操作不当,可能会引发短暂的服务发现问题。 下面我们从Eureka的核心工作原理来详细分析这个问题。 Eureka的…...

2025季度云服务器排行榜
在全球云服务器市场,各厂商的排名和地位并非一成不变,而是由其独特的优势、战略布局和市场适应性共同决定的。以下是根据2025年市场趋势,对主要云服务器厂商在排行榜中占据重要位置的原因和优势进行深度分析: 一、全球“三巨头”…...