Skip to content

Commit 6885f25

Browse files
committed
Use UnmanagedMemoryStream instead of MemoryStream
1 parent b77ba9a commit 6885f25

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/LanguageIdentification/LanguageIdentification.csproj

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
<PackageReadmeFile>readme.md</PackageReadmeFile>
1515

1616
<GenerateDocumentationFile>true</GenerateDocumentationFile>
17+
18+
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
1719
</PropertyGroup>
1820

1921
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">

src/LanguageIdentification/LanguageIdentificationModel.cs

+19-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.IO;
66
using System.IO.Compression;
77
using System.Linq;
8+
using System.Runtime.InteropServices;
89
using System.Runtime.Serialization;
910
using System.Text;
1011

@@ -321,10 +322,24 @@ private static LanguageIdentificationModel InternalLoadDefaultModel()
321322
else
322323
{
323324
//解压后MemoryStream长度为 7649400 ,初始化一个 7700000 大小的数组,保留一点冗余
324-
using var unzipedStream = new MemoryStream(7700000);
325-
gzipStream.CopyTo(unzipedStream);
326-
unzipedStream.Seek(0, SeekOrigin.Begin);
327-
return Deserialize(unzipedStream);
325+
const int BufferSize = 7700000;
326+
327+
//使用非托管内存,以便手动释放
328+
var unmanagePtr = Marshal.AllocHGlobal(BufferSize);
329+
try
330+
{
331+
unsafe
332+
{
333+
using var unzipedStream = new UnmanagedMemoryStream((byte*)unmanagePtr.ToPointer(), 0, BufferSize, FileAccess.ReadWrite);
334+
gzipStream.CopyTo(unzipedStream);
335+
unzipedStream.Seek(0, SeekOrigin.Begin);
336+
return Deserialize(unzipedStream);
337+
}
338+
}
339+
finally
340+
{
341+
Marshal.FreeHGlobal(unmanagePtr);
342+
}
328343
}
329344
}
330345

0 commit comments

Comments
 (0)