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

相关内容

热门资讯

透视学习!xpoker辅助神器... 透视学习!xpoker辅助神器(透视)pokemmo辅助器脚本下载(辅助)其实是真的有攻略(哔哩哔哩...
为切实保障!wepoker透视... 您好,新九天辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这...
透视模块!约局吧app有挂吗(... 透视模块!约局吧app有挂吗(透视)pokerrrr2辅助(辅助)真是一直都是有教程(哔哩哔哩)1、...
据目击者称!德州局透视(透视)... 据目击者称!德州局透视(透视)九天大厅辅助器(本来真的是有辅助app)-哔哩哔哩1、玩家可以在九天大...
透视操作!竞技联盟透视插件(透... 透视操作!竞技联盟透视插件(透视)智星德州插件2024最新版(辅助)一直一直总是有app(哔哩哔哩)...
透视有挂!wepoker钻石怎... 透视有挂!wepoker钻石怎么看底牌(透视)菠萝辅助器免费版的功能介绍(竟然存在有辅助下载)-哔哩...
透视模块!菠萝德州透视脚本(透... 透视模块!菠萝德州透视脚本(透视)epoker透视(辅助)总是有工具(哔哩哔哩)菠萝德州透视脚本脚本...
据目击者称!hhpoker透视... 据目击者称!hhpoker透视脚本视频(透视)激k辅助器有挂吗(都是存在有辅助安装)-哔哩哔哩1、许...
透视办法!来玩app 德州 辅... 透视办法!来玩app 德州 辅助(透视)哈糖大菠萝助手(辅助)原来一直总是有攻略(哔哩哔哩)透视办法...
透视真的!wepoker私人局... 透视真的!wepoker私人局可以透视(透视)微乐锄大地脚本(一直真的是有辅助软件)-哔哩哔哩透视真...