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

相关内容

热门资讯

今天下午!红龙poker辅助平... 今天下午!红龙poker辅助平台,We poker辅助器下载(透视)关于教程(真实有挂)-哔哩哔哩1...
截至目前!新星游辅助软件试用版... 截至目前!新星游辅助软件试用版,拱趴大菠萝辅助神器,举措教程(有挂助手)-哔哩哔哩1、新星游辅助软件...
今年以来!aapoker怎么拿... 今年以来!aapoker怎么拿好牌,wepoker私人局透视方法(透视)开挂教程(有挂分享)-哔哩哔...
于此同时!丽水都来脚本辅助,a... 于此同时!丽水都来脚本辅助,aapoker能控制牌吗,手段教程(了解有挂)-哔哩哔哩1、每一步都需要...
透视最新!wepoker一直输... 透视最新!wepoker一直输的号能继续打吗,wepoker免费脚本弱密码(透视)必备教程(真的有挂...
来临!wepoker透视器免费... 您好,微乐内蒙古自建房脚本免费下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【4852750...
今年以来!wepoker透视脚... 今年以来!wepoker透视脚本安卓,wepoker插件功能辅助器(透视)专业教程(有人有挂)-哔哩...
一直以来!免费雀神挂件怎么安装... 一直以来!免费雀神挂件怎么安装,新九哥脚本下载,教程书教程(发现有挂)-哔哩哔哩1、用户打开应用后不...
不少玩家反映!线上德州的辅助器... 不少玩家反映!线上德州的辅助器是什么,wepoker轻量版透视系统(透视)必备教程(竟然有挂)-哔哩...
围绕透视问题!友间十三道有什么... 围绕透视问题!友间十三道有什么窍门,微乐小程序辅助开发,指南教程(有挂教学)-哔哩哔哩1、进入到友间...