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

相关内容

热门资讯

第7分钟外挂!欢聚水鱼脚本下载... 您好,欢聚水鱼脚本下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩...
5分钟外挂!诸暨翻财神攻略,九... 5分钟外挂!诸暨翻财神攻略,九九山城万州版辅助,靠谱教程(有挂攻略)-哔哩哔哩运九九山城万州版辅助辅...
六分钟外挂!雀神广东麻将透视视... 您好,雀神广东麻将透视视频这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
7分钟外挂!嘟咪互动修改器,新... 7分钟外挂!嘟咪互动修改器,新祥心有挂吗,德州教程(有挂解惑)-哔哩哔哩1、游戏颠覆性的策略玩法,独...
6分钟外挂!h5新全游辅助,禅... 6分钟外挂!h5新全游辅助,禅游指尖四川修改器,细节揭秘(了解有挂)-哔哩哔哩1、每一步都需要思考,...
一分钟外挂!如何设置财神十三章... 一分钟外挂!如何设置财神十三章的辅助功能,天天爱柳州辅助,教你攻略(有挂方针)-哔哩哔哩1、玩家可以...
八分钟外挂!方片十三张外卦,创... 八分钟外挂!方片十三张外卦,创思维激k看底牌辅助,德州论坛(有挂秘籍)-哔哩哔哩亲,关键说明,创思维...
4分钟外挂!玩吧辅助工具,新天... 4分钟外挂!玩吧辅助工具,新天道挂机辅助,2025新版教程(真的有挂)-哔哩哔哩新天道挂机辅助是一种...
第8分钟外挂!陕西奇迹打锅子破... 第8分钟外挂!陕西奇迹打锅子破解,逸趣鄱阳翻精辅助,科技教程(有挂教学)-哔哩哔哩1、进入游戏-大厅...
第5分钟外挂!圣盛鄂州晃晃辅助... 第5分钟外挂!圣盛鄂州晃晃辅助,决战卡五星辅助修改器,科技教程(真的有挂)-哔哩哔哩决战卡五星辅助修...