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

相关内容

热门资讯

免费测试版"微信小程... 免费测试版"微信小程序牵手辅助"开挂(透视)辅助平台(其实是真的有挂的)-哔哩哔哩;微信小程序牵手辅...
5分钟带你了解!麻友圈安全版插... 您好:麻友圈安全版插件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
八分钟带你发现!蜀山四川破解好... 蜀山四川破解好友版辅助是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以...
一分钟揭秘"创思维激... 一分钟揭秘"创思维激k透视挂"开挂(透视)辅助安装(原来确实是有挂)-哔哩哔哩;最新版2026是一款...
第六分钟带你了解!牵手跑得软件... 第六分钟带你了解!牵手跑得软件(透视挂)透视神器外挂开挂辅助平台(果然有挂);无需打开直接搜索加(薇...
第2分钟带你辅助!网易棋牌辅助... 大家好,今天小编来为大家解答网易棋牌辅助器这个问题咨询软件客服可以免费测试直接加微信(1367043...
终于懂了"广西老友玩... 《终于懂了"广西老友玩游戏辅助器"开挂(透视)辅助插件(果然确实有挂的)-哔哩哔哩》 广西老友玩游戏...
三分钟带你了解!小程序66徐州... 三分钟带你了解!小程序66徐州辅助(透视挂)查到实测外挂开挂辅助工具(原来真的有挂);无需打开直接搜...
第一分钟带你开挂!浙江宝宝游戏... 第一分钟带你开挂!浙江宝宝游戏辅助器,贪吃蛇辅助器2022,曝光教程(真是有挂)-哔哩哔哩【无需打开...
盘点一款"拱趴大菠萝... 《盘点一款"拱趴大菠萝有辅助工具吗"开挂(透视)辅助平台(果然是有挂的)-哔哩哔哩》 拱趴大菠萝有辅...