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

相关内容

热门资讯

据悉!wepoker免费透视,... 据悉!wepoker免费透视,德普之星辅助软件,真是存在有挂(竟然有挂)1、德普之星辅助软件免费脚本...
总算了解!pokemmo脚本手... 总算了解!pokemmo脚本手机版,智星菠萝可以辅助吗,都是有挂(有挂助手)一、可以开透视的定义与意...
明白辅助挂!约局吧如何查看是否... 明白辅助挂!约局吧如何查看是否有挂,德扑之星透视辅助插件,切实是有挂(有挂助手)1、德扑之星透视辅助...
重大通报!德普之星的辅助工具介... 重大通报!德普之星的辅助工具介绍,hhpoker怎么防作弊,果然是真的有挂(有挂详情)1、进入到是否...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker破解器激活码,德扑软件,其实确实有挂(竟然有挂)1、用户打开应用后不...
揭秘一下!xpoker怎么作弊... 揭秘一下!xpoker怎么作弊,hhpoker可以开挂吗,总是真的是有挂(有挂秘诀)所有人都在同一条...
据玩家消息!aapoker俱乐... 据玩家消息!aapoker俱乐部靠谱吗,德普之星透视辅助软件是真的吗,一直确实有挂(有挂教程)1、让...
重大通报!hh poker辅助... 重大通报!hh poker辅助器先试用,wejoker辅助器怎么卖,真是真的有挂(真实有挂);1、在...
截至发稿!德普之星有透视辅助吗... 截至发稿!德普之星有透视辅助吗,德普辅助器怎么用,切实真的是有挂(有挂总结)1、每一步都需要思考,不...
玩家亲测!hhpoker为什么... 玩家亲测!hhpoker为什么一直输,hhpoker辅助器,总是真的是有挂(有挂教程)脚本下载中分为...