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

相关内容

热门资讯

透视透视!wejoker辅助脚... 透视透视!wejoker辅助脚本(透视)决战十水三辅助(其实存在有辅助平台)-哔哩哔哩亲,关键说明,...
最新消息!pokemmo辅助器... 最新消息!pokemmo辅助器手机版下载(透视)湖北逍遥卡五星辅助(切实真的有辅助平台)-哔哩哔哩1...
透视玄学!wejoker免费脚... 透视玄学!wejoker免费脚本(透视)悠闲游戏辅助(本来是有辅助app)-哔哩哔哩1、悠闲游戏辅助...
据相关数据显示!wpk透视辅助... 据相关数据显示!wpk透视辅助(透视)开心十三张有没有挂(原来存在有辅助平台)-哔哩哔哩运开心十三张...
此事备受玩家关注!werpla... 此事备受玩家关注!werplan怎么作必弊(透视)微信小程序微乐破解器(一直有辅助下载)-哔哩哔哩1...
今年以来!wepoker私局代... 今年以来!wepoker私局代打(透视)潮汕汇app透视软件(一直是真的辅助工具)-哔哩哔哩1、实时...
今日!wpk作必弊是真的吗(透... 今日!wpk作必弊是真的吗(透视)随意玩有没有辅助(切实真的是有辅助修改器)-哔哩哔哩1、进入到随意...
透视教程!wepoker辅助器... 透视教程!wepoker辅助器最新版本更新内容(透视)超级三加一辅助工具安装(其实有辅助工具)-哔哩...
透视系统!大菠萝789辅助器下... 透视系统!大菠萝789辅助器下载(透视)兴动互娱辅助贴吧开挂(真是是真的辅助辅助器)-哔哩哔哩兴动互...
透视辅助!pokemmo手机脚... 透视辅助!pokemmo手机脚本(透视)闲来游戏辅助器脚本(切实是真的辅助app)-哔哩哔哩1)闲来...