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

相关内容

热门资讯

7分钟了解!青龙大厅牛牛透视辅... 7分钟了解!青龙大厅牛牛透视辅助,吉祥棋牌填大坑科技有挂吗,力荐教程(有挂总结)1、下载好吉祥棋牌填...
三分钟了解!中州游戏有挂吗,网... 三分钟了解!中州游戏有挂吗,网易棋牌数据透视,爆料教程(有挂透视)1)网易棋牌数据透视辅助挂:进一步...
6分钟了解!中至吉安小程序有挂... 6分钟了解!中至吉安小程序有挂吗,熊猫麻将跑得快有挂没,实用技巧(有挂方法);1、打开软件启动之后找...
9分钟了解!大晋游戏的外 挂,... 9分钟了解!大晋游戏的外 挂,心悦海南,揭秘攻略(有挂辅助)1、每一步都需要思考,不同水平的挑战会更...
4分钟了解!兴动棋牌看牌,西兵... 4分钟了解!兴动棋牌看牌,西兵互娱辅助是真是假,必胜教程(有挂方法)1、首先打开西兵互娱辅助是真是假...
三分钟了解!蜀州游戏麻将有挂没... 三分钟了解!蜀州游戏麻将有挂没,畅享徐州麻将神器,微扑克教程(有挂方法)蜀州游戏麻将有挂没是一种具有...
四分钟了解!六瓣数字消字牌外 ... 四分钟了解!六瓣数字消字牌外 挂,天天仙桃麻将有挂,可靠教程(有挂方法)六瓣数字消字牌外 挂是一种具...
9分钟了解!桂林字牌辅助器,老... 9分钟了解!桂林字牌辅助器,老友十三张有辅助挂吗,可靠教程(有挂脚本);老友十三张有辅助挂吗辅助器中...
8分钟了解!jj斗地主助赢神器... 8分钟了解!jj斗地主助赢神器,金州水鱼免费辅助软件,必胜教程(有挂教学);1、任何金州水鱼免费辅助...
4分钟了解!同城游510k有挂... 4分钟了解!同城游510k有挂吗,同乡游戏有挂吗,高科技教程(有挂解说)1、同城游510k有挂吗透视...