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

相关内容

热门资讯

透视讲解!wpk私人局有透视吗... 您好,wepoker透视辅助下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
透视app!红龙poker有辅... 透视app!红龙poker有辅助吗(透视)开挂辅助器(果然存在有挂)-哔哩哔哩所有人都在同一条线上,...
透视辅助!epoker透视底牌... 透视辅助!epoker透视底牌,哈糖大菠萝开挂,阶段教程(总是是有挂)-哔哩哔哩1、玩家可以在哈糖大...
透视插件!wepoker辅助器... 透视插件!wepoker辅助器激活码(透视)开挂辅助器(其实有挂)-哔哩哔哩1)wepoker辅助器...
透视教程!hhpoker德州挂... 透视教程!hhpoker德州挂真的有吗,werplan透视挂,学习教程(一贯存在有挂)-哔哩哔哩1、...
透视游戏!aapoker免费透... 透视游戏!aapoker免费透视脚本,xpoker辅助工具,诀窍教程(一贯存在有挂)-哔哩哔哩1)a...
透视大厅!aa poker透视... 透视大厅!aa poker透视软件(透视)开挂辅助器(原来是有挂)-哔哩哔哩1、超多福利:超高返利,...
透视脚本!xpoker辅助工具... 透视脚本!xpoker辅助工具,pokernow辅助工具,方案教程(一贯真的有挂)-哔哩哔哩1、不需...
透视修改器!wepoker透视... 透视修改器!wepoker透视有吗(透视)开挂辅助神器(竟然是有挂)-哔哩哔哩wepoker透视有吗...
透视科技!wejoker透视方... 透视科技!wejoker透视方法,wepoker线上大神,操作教程(确实存在有挂)-哔哩哔哩在进入w...