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

相关内容

热门资讯

透视插件!hhpoker透视下... 透视插件!hhpoker透视下载链接在哪里,云扑克有透视吗,必胜教程(先前是真的有挂);支持多人共享...
透视ai!wepoker作弊辅... 透视ai!wepoker作弊辅助,wpk辅助哪里买,存在挂教程(原先真的是有挂);实战中需综合运用上...
透视透视挂!wpk透视辅助软件... 透视透视挂!wpk透视辅助软件,epoker透视底牌,攻略教程(从来是有挂);原来确实真的有挂(需添...
透视神器!德普之星app安卓版... 透视神器!德普之星app安卓版破解版,德普之星有辅助软件吗,总结教程(最初真的有挂),亲,有的,ai...
透视代打!智星德州菠萝安装,哈... 透视代打!智星德州菠萝安装,哈糖大菠萝怎么挂,2025教程(先前是有挂)是一款可以让一直输的玩家,快...
透视苹果版!wepoker透视... 透视苹果版!wepoker透视脚本,wepoker钻石怎么看底牌,透明挂教程(起初真的有挂);是一款...
透视脚本!wepoker辅助透... 透视脚本!wepoker辅助透视软件,fishpoker透视,规律教程(一贯是有挂)1、很好的工具软...
透视科技!wpk透视脚本,德普... 德普之星透视辅助软件新手教程相关信息汇总(需添加指定Q群1067239143获取下载链接);透视科技...
透视软件!wpk透视脚本下载,... 透视软件!wpk透视脚本下载,wepoker辅助脚本,安装教程(一直有挂);原来确实真的有挂(需添加...
透视好牌!wepoker免费永... 透视好牌!wepoker免费永久脚本,购买wepoker模拟器,2025新版技巧(先前真的有挂)关于...