当前位置:网站首页>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;// length
IntPtr 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 uncertain
p = 2;
Marshal.StructureToPtr(p,t,false);
p = Marshal.PtrToStructure<int>(t);
Console.WriteLine("p " + p);//2
// Traverse
Console.WriteLine(" Traverse ");
for (int i = 0; i < 10; i++)
{
t = buffer + i * sizeof(int);
Console.WriteLine(Marshal.PtrToStructure<int>(t));
}
Traverse :
43909312
44502144
2
0
0
24
1357220181
196712
550912
543686656
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;// length
IntPtr 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 module
Trying 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;// length
IntPtr 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 .
边栏推荐
- GCC [7] - compilation checks the declaration of functions, and link checks the definition bugs of functions
- Word如何显示修改痕迹
- If you have any problems, you can contact me. A rookie ~
- php+redis实现超时取消订单功能
- How are you in the first half of the year occupied by the epidemic| Mid 2022 summary
- R语言ggplot2可视化:使用ggpubr包的ggstripchart函数可视化分组点状条带图(dot strip plot)、设置add参数为不同水平点状条带图添加箱图
- Reptiles have a good time. Are you full? These three bottom lines must not be touched!
- Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
- LeetCode-1279. 红绿灯路口
- The second day of rhcsa study
猜你喜欢
黑馬--Redis篇
受益匪浅,安卓面试问题
应用使用Druid连接池经常性断链问题分析
Visual Studio Code启动时提示“Code安装似乎损坏。请重新安装。”、标题栏显示“不受支持”信息的解决办法
How to type multiple spaces when editing CSDN articles
JDBC详解
ROS custom message publishing subscription example
Based on butterfly species recognition
Three years of Android development, Android interview experience and real questions sorting of eight major manufacturers during the 2022 epidemic
A wearable arm device for night and sleeveless blood pressure measurement [translation]
随机推荐
wx小程序学习笔记day01
Meilu biological IPO was terminated: the annual revenue was 385million, and Chen Lin was the actual controller
助力安全人才专业素养提升 | 个人能力认证考核第一阶段圆满结束!
Problems encountered in using RT thread component fish
Countdown 2 days | live broadcast preview of Tencent cloud message queue data import platform
Characteristic colleges and universities, jointly build Netease Industrial College
Handwritten online chat system (principle part 1)
In 50W, what have I done right?
AIRIOT物联网平台赋能集装箱行业构建【焊接工位信息监控系统】
三年Android开发,2022疫情期间八家大厂的Android面试经历和真题整理
pychrm社区版调用matplotlib.pyplot.imshow()函数图像不弹出的解决方法
Analysis of frequent chain breaks in applications using Druid connection pools
PMP每日一练 | 考试不迷路-7.6
R language ggplot2 visualization: use the ggdotplot function of ggpubr package to visualize dot plot, set the palette parameter, and set the colors of data points and box graphs of dot plots at differ
Digital "new" operation and maintenance of energy industry
About static type, dynamic type, ID, instancetype
Test technology stack arrangement -- self cultivation of test development engineers
第五期个人能力认证考核通过名单公布
Unlock 2 live broadcast themes in advance! Today, I will teach you how to complete software package integration Issues 29-30
Three years of Android development, Android interview experience and real questions sorting of eight major manufacturers during the 2022 epidemic