当前位置:网站首页>C # use Marshall to manually create unmanaged memory in the heap and use
C # use Marshall to manually create unmanaged memory in the heap and use
2022-07-06 19:16:00 【luckyone906】
Use Marshal Make a large array that can quickly free memory .
You need to constantly apply for a large memory array , Then release him , however C# For large memory, it is not released immediately , So there are some performance problems .
In the blog Garden, I saw a great God using Marshal A large array of quick applications , So I learned his way to get one . This article tells you how this class is used
In use , Let's take a look at the original C# Large array performance . You can see that it keeps gc, Poor performance
static void Main(string[] args){for (int i = 0; i < 10000; i++){Foo();}Console.ReadKey();}private static void Foo(){var foo = new byte[1000000000];}
Introduce
In the use of Marshal You need to know what this is , Actually Marshal Is an offer COM Methods of interoperability .
Use
Here's a quick application int Array to tell you how to use .
Do you remember C Application array for ? In fact, the following methods and C In the same
int n = 100000;// lengthIntPtr buffer = Marshal.AllocHGlobal(sizeof(int) * n);
It can be used at this time buffer As an array
Here's his first k Elements modified
IntPtr buffer = Marshal.AllocHGlobal(sizeof(int) * n);int k = 2;IntPtr t = buffer + k * sizeof(int);var p = Marshal.PtrToStructure<int>(t);Console.WriteLine("p " + p); //196713 The value is uncertainp = 2;Marshal.StructureToPtr(p,t,false);p = Marshal.PtrToStructure<int>(t);Console.WriteLine("p " + p);//2// TraverseConsole.WriteLine(" Traverse ");for (int i = 0; i < 10; i++){t = buffer + i * sizeof(int);Console.WriteLine(Marshal.PtrToStructure<int>(t));}
Traverse :
4390931244502144200241357220181196712550912543686656
As you can see from the code above , The two main methods used are StructureToPtr and PtrToStructure , and StructureToPtr Is to write from the specified type to the pointer , I hope you also know how to use pointers ,PtrToStructure Is to start reading data from where the pointer points , Read the specified type of data . So you can go from Marshal Use one type to read from another , However, generally, the type to be read needs to be determined by the type size , Such as char Sure 、string Can not be .
In turn, ,StructureToPtr Is to write the specified type to the specified pointer , It is also necessary to determine the size of this type , If you can write char But you can't write string. This is how to read and write arrays .
So when traversing, what output some strange values , In fact, because there is no initialization , The value inside is uncertain . I think it's good to use this as a random number .
Use Marshal It's safer , because ms Did a lot of processing , But it also causes the program to flash back , Like the following code
private static void Foo(){int n = 100000;// lengthIntPtr buffer = Marshal.AllocHGlobal(sizeof(int) * n);try{var t = buffer + (n * 10) * sizeof(int);var p = Marshal.PtrToStructure<int>(t);}catch (Exception e){Console.WriteLine(e);}Marshal.FreeHGlobal(buffer);}
There will be anomalies System.AccessViolationException, This exception cannot be catch Of , So you'd better encapsulate it when you use it
“System.AccessViolationException” The unhandled exception of type Unknown moduleTrying to read or write to protected memory . This usually indicates that other memory is corrupted
if necessary catch Then please app.config Add the following code
<?xml version="1.0" encoding="utf-8" ?><configuration><runtime><legacyCorruptedStateExceptionsPolicy enabled="true" /></runtime></configuration>
And then in Main Function add HandleProcessCorruptedStateExceptions , Please look at the code.
[HandleProcessCorruptedStateExceptions]static void Main(string[] args){AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;for (int i = 0; i < 100000; i++){try{Foo();}catch (Exception e){Console.WriteLine(e);}}Console.WriteLine(" complete ");Console.ReadKey();}
Then you can see entering UnhandledException , But I can't catch , The software will still crash
Free memory
So how to free memory ? Because this application is not managed , If there is no manual release , Then there is a memory leak .
static void Main(string[] args){for (int i = 0; i < 10000; i++){Foo();}Console.ReadKey();}private static void Foo(){int n = 100000;// lengthIntPtr buffer = Marshal.AllocHGlobal(sizeof(int) * n);}
The above code will soon see that the memory is occupied by 2G, So you need to release it manually
Marshal.FreeHGlobal(buffer);
The original byte Arrays need to use 1G Memory , And it's very slow , Now using this method only needs 7M Memory , fast
So when you need to apply for a large array , Need to keep releasing , You can use this method .
边栏推荐
- Pychrm Community Edition calls matplotlib pyplot. Solution of imshow() function image not popping up
- AutoCAD - what is the default lineweight for centerline drawing and CAD? Can I modify it?
- R language uses rchisq function to generate random numbers that conform to Chi square distribution, and uses plot function to visualize random numbers that conform to Chi square distribution
- ROS自定义消息发布订阅示例
- Oracle advanced (IV) table connection explanation
- 全套教学资料,阿里快手拼多多等7家大厂Android面试真题
- 倒计时2天|腾讯云消息队列数据接入平台(Data Import Platform)直播预告
- C#/VB. Net to add text / image watermarks to PDF documents
- English topic assignment (25)
- A wearable arm device for night and sleeveless blood pressure measurement [translation]
猜你喜欢

Oracle advanced (IV) table connection explanation

ROS custom message publishing subscription example
Three years of Android development, Android interview experience and real questions sorting of eight major manufacturers during the 2022 epidemic

包装行业商业供应链管理平台解决方案:布局智慧供应体系,数字化整合包装行业供应链

Xingnuochi technology's IPO was terminated: it was planned to raise 350million yuan, with an annual revenue of 367million yuan

Solution of commercial supply chain management platform for packaging industry: layout smart supply system and digitally integrate the supply chain of packaging industry
![[depth first search] Ji suanke: Square](/img/fc/e42ae0d036be258bed5623d55fc2db.jpg)
[depth first search] Ji suanke: Square

Word如何显示修改痕迹
![Noninvasive and cuff free blood pressure measurement for telemedicine [translation]](/img/56/8deaec18cd9f2cf49ff234b09b1283.png)
Noninvasive and cuff free blood pressure measurement for telemedicine [translation]

Problems encountered in using RT thread component fish
随机推荐
多线程基础:线程基本概念与线程的创建
An error occurs when installing MySQL: could not create or access the registry key needed for the
Problems encountered in using RT thread component fish
Druid 数据库连接池 详解
About NPM install error 1
Binary search tree
A full set of teaching materials, real questions of Android interview of 7 major manufacturers including Alibaba Kwai pinduoduo
openmv4 学习笔记1----一键下载、图像处理背景知识、LAB亮度-对比度
Airiot IOT platform enables the container industry to build [welding station information monitoring system]
抽象类与抽象方法
The second day of rhcsa study
主从搭建报错:The slave I/O thread stops because master and slave have equal MySQL serv
R语言使用dt函数生成t分布密度函数数据、使用plot函数可视化t分布密度函数数据(t Distribution)
QLabel 跑马灯文字显示
ACTF 2022圆满落幕,0ops战队二连冠!!
Sanmian ant financial successfully got the offer, and has experience in Android development agency recruitment and interview
Detailed idea and code implementation of infix expression to suffix expression
黑馬--Redis篇
R language ggplot2 visualization: use the ggstripchart function of ggpubr package to visualize the grouped dot strip plot, and set the add parameter to add box plots for different levels of dot strip
保证接口数据安全的10种方案