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

相关内容

热门资讯

普及透视!werplan怎么作... 普及透视!werplan怎么作必弊,sohoo poker辅助(透视)一直一直都是有辅助插件(哔哩哔...
据通报!菠萝辅助器免费版的特点... 据通报!菠萝辅助器免费版的特点,广西老友辅助app,其实存在有辅助教程(哔哩哔哩)1、玩家可以在菠萝...
关于透视!impoker辅助,... 关于透视!impoker辅助,哈糖大菠萝攻略(透视)竟然是真的有辅助工具(哔哩哔哩);暗藏猫腻,小编...
目前!德州透视是真的假的,微乐... 目前!德州透视是真的假的,微乐小程序授权,一直有辅助插件(哔哩哔哩)1、完成德州透视是真的假的辅助器...
专业透视!菠萝德州透视脚本,拱... 专业透视!菠萝德州透视脚本,拱趴大菠萝十三水作必弊(透视)都是真的有辅助软件(哔哩哔哩)拱趴大菠萝十...
据权威媒体报道!hhpoker... 据权威媒体报道!hhpoker可以控制吗,微乐兰州麻将小程序辅助,好像是有辅助脚本(哔哩哔哩)1、微...
总结透视!pokemmo手机脚... 总结透视!pokemmo手机脚本,德州局透视脚本下载安装最新版本(透视)总是有辅助神器(哔哩哔哩)1...
最终!wpk免费辅助,佛手十三... 最终!wpk免费辅助,佛手十三道作必弊码,其实是有辅助教程(哔哩哔哩)一、佛手十三道作必弊码游戏安装...
曝光透视!哈糖大菠萝怎么挂,拱... 曝光透视!哈糖大菠萝怎么挂,拱趴大菠萝挂哪里(透视)一贯一直都是有辅助攻略(哔哩哔哩)一、拱趴大菠萝...
在玩家背景下!hhpoker是... 在玩家背景下!hhpoker是真的假的,潮汕汇木虱鱼辅助,原来真的是有辅助教程(哔哩哔哩)1)潮汕汇...