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

相关内容

热门资讯

第2分钟了解(wpk德州)黑科... 第2分钟了解(wpk德州)黑科技透明挂辅助插件(透视)解密教程(2021已更新)(哔哩哔哩)是一款可...
第7分钟了解(德扑之星数据)软... 第7分钟了解(德扑之星数据)软件透明挂辅助神器(透视)详细教程(2020已更新)(哔哩哔哩)相信很多...
第十分钟了解(wpk作弊)外挂... 您好:wpk作弊这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
第9分钟了解(德州之星手游)黑... 第9分钟了解(德州之星手游)黑科技透明挂辅助ai(透视)软件教程(2020已更新)(哔哩哔哩);亲,...
三分钟了解(微扑克工具)外挂智... 三分钟了解(微扑克工具)外挂智能ai辅助安装(透视)辅助教程(2022已更新)(哔哩哔哩);三分钟了...
六分钟了解(wePoKe)黑科... 六分钟了解(wePoKe)黑科技透明挂辅助安装(透视)AI教程(2020已更新)(哔哩哔哩)相信很多...
1分钟了解(Wepoke是真的... 1分钟了解(Wepoke是真的)软件透明挂辅助下载(透视)wepoke教程(2022已更新)(哔哩哔...
第七分钟了解(aapOKER)... 第七分钟了解(aapOKER)黑科技透明挂辅助下载(透视)软件教程(2022已更新)(哔哩哔哩);大...
五分钟了解(拱趴大菠萝)软件透... 您好:拱趴大菠萝这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
第七分钟了解(aapOker)... 第七分钟了解(aapOker)外挂辅助插件安装软件(透视)必胜教程(2024已更新)(哔哩哔哩);1...