ASP.NetSafeHandle-tasksandexamples
创始人
2024-09-19 10:01:05
0

ASP.Net中的SafeHandle类可用于管理外部资源,如文件句柄、内存句柄等。下面是一些使用SafeHandle的示例:

  1. 管理文件句柄
public class FileSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private readonly string _fileName;

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern IntPtr CreateFile(
        string lpFileName,
        FileAccess dwDesiredAccess,
        FileShare dwShareMode,
        IntPtr lpSecurityAttributes,
        FileMode dwCreationDisposition,
        FileAttributes dwFlagsAndAttributes,
        IntPtr hTemplateFile);

    public FileSafeHandle(string fileName)
        : base(true)
    {
        _fileName = fileName;
        handle = CreateFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero,
            FileMode.Open, FileAttributes.RandomAccess, IntPtr.Zero);
        if (handle == IntPtr.Zero || handle == new IntPtr(-1))
        {
            int lastWin32Error = Marshal.GetLastWin32Error();
            throw new Win32Exception(lastWin32Error, "Failed to open file");
        }
    }

    protected override bool ReleaseHandle()
    {
        return NativeMethods.CloseHandle(handle);
    }

    public string FileName => _fileName;
}

在使用FileSafeHandle时,只需像使用一般的文件句柄一样使用即可,无需手动释放句柄。

  1. 管理内存句柄
public class MemorySafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private readonly long _memorySize;

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize,
        AllocationType flAllocationType, MemoryProtection flProtect);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize,
        FreeType dwFreeType);

    public MemorySafeHandle(long memorySize)
        : base(true)
    {
        _memorySize = memorySize;
        handle = VirtualAlloc(IntPtr.Zero, new UIntPtr((ulong)memorySize),
            Allocation

相关内容

热门资讯

第十分钟神器!微乐小程序黑科技... 您好,微乐小程序黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
透视教程!微乐小程序黑科技,微... 透视教程!微乐小程序黑科技,微乐小程序脚本入口(透视)确实是真的挂(哔哩哔哩)1、这是跨平台的微乐小...
第二分钟辅助!微乐小程序黑科技... 第二分钟辅助!微乐小程序黑科技,微乐游戏小程序脚本(开挂)本来有挂(2026)在进入微乐小程序黑科技...
黑科技技巧!微乐小程序黑科技,... 黑科技技巧!微乐小程序黑科技,微乐自建房辅助工具下载入口在哪(透视)果然是真的挂(哔哩哔哩)黑科技技...
七分钟插件!微乐小程序免费黑科... 七分钟插件!微乐小程序免费黑科技,微乐小程序黑科技免费知乎(开挂)原来存在有挂(2026)1、上手简...
透视能赢!微乐小程序免费黑科技... 透视能赢!微乐小程序免费黑科技,微乐手游脚本辅助(透视)真是有挂(哔哩哔哩)1.微乐小程序免费黑科技...
第一分钟工具!微乐小程序免费黑... 第一分钟工具!微乐小程序免费黑科技,广西微乐小程序辅助器(开挂)总是有挂(2026)1、微乐小程序免...
今年以来!微乐小程序黑科技,广... 今年以来!微乐小程序黑科技,广西微乐小程序控制器(透视)切实有挂(哔哩哔哩)1)广西微乐小程序控制器...
4分钟透视!微乐小程序免费黑科... 您好,微乐小程序免费黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
6分钟工具!微乐小程序黑科技,... 6分钟工具!微乐小程序黑科技,微乐游戏公众号辅助器(开挂)总是真的是有挂(2026)1、每一步都需要...