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

相关内容

热门资讯

记者爆料!打哈儿床将作弊(辅助... 记者爆料!打哈儿床将作弊(辅助挂)德扑之心免费透视(从前是真的有挂);1、许多玩家不知道打哈儿床将作...
分享实测!情怀游戏辅助器破解版... 分享实测!情怀游戏辅助器破解版(辅助挂)hhpoker可以控制吗(其实是有挂);情怀游戏辅助器破解版...
一分钟了解!微乐辅助脚本(辅助... 一分钟了解!微乐辅助脚本(辅助挂)wpk透视是真的假的(一直有挂);1.微乐辅助脚本 ai辅助创建新...
一分钟了解!火神辅助免费下载(... 一分钟了解!火神辅助免费下载(辅助挂)wepoker辅助软件价格(往昔真的有挂)是一款可以让一直输的...
必备科技!天蝎辅助(辅助挂)德... 必备科技!天蝎辅助(辅助挂)德扑HHpoker有挂吗(确实是真的有挂);天蝎辅助辅助器中分为三种模型...
必知教程!陕西扣点点脚本辅助器... 必知教程!陕西扣点点脚本辅助器(辅助挂)wepoker私人局辅助挂(固有真的是有挂);亲,有的,ai...
终于清楚!卡农大厅辅助(辅助挂... 您好:卡农大厅辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
攻略讲解!雀友会广东潮汕麻雀开... 攻略讲解!雀友会广东潮汕麻雀开挂(辅助挂)pokermaster修改器(起初存在有挂);1.雀友会广...
关于!微乐手游微乐辅助免费(辅... 关于!微乐手游微乐辅助免费(辅助挂)wepoker怎么破解游戏(切实是有挂);是一款可以让一直输的玩...