gpt4 book ai didi

c# - 方法在 3310 次成功后失败

转载 作者:太空狗 更新时间:2023-10-30 00:48:22 24 4
gpt4 key购买 nike

我继承了以下扩展方法,它根据文件路径创建一个 ImageSource 对象

public static class ImageSourceExtensions
{
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};

public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0;

[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

public static ImageSource GetIconFromFolder(this string filePath)
{
SHFILEINFO shinfo = new SHFILEINFO();
SHGetFileInfo(filePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo),
SHGFI_ICON | SHGFI_LARGEICON);

using (Icon i = Icon.FromHandle(shinfo.hIcon))
{
//Convert icon to a Bitmap source
ImageSource img = Imaging.CreateBitmapSourceFromHIcon(
i.Handle,
new Int32Rect(0, 0, i.Width, i.Height),
BitmapSizeOptions.FromEmptyOptions());

return img;
}
}
}

此扩展方法对文件夹和文件均适用 3310 次。在第 3311 次方法调用时,抛出以下异常:

'Win32 handle that was passed to Icon is not valid or is the wrong type'

使用 shinfo.hIcon 属性时会抛出此错误。

错误最初是在我的主应用程序中引发的,并且每次都在不同的文件中。从那以后,我将此类提取到一个新项目中,并且可以通过单击按钮执行此操作来抛出相同的错误(在相同的次数之后):

String path = @"C:\Generic Folder\Generic Document.pdf";

for (int i = 0; i <4000; i++)
{
ImageSource img = path.GetIconFromFolder();
}

有人知道造成这种情况的明显原因吗?

最佳答案

您的 HANDLE 已用完。 Windows 的句柄数量有限,当您获得一个句柄(在本例中为图标句柄)时,您应该在不再使用它后释放它。如果不这样做,Windows 将用完可用的句柄。

If SHGetFileInfo returns an icon handle in the hIcon member of the SHFILEINFO structure pointed to by psfi, you are responsible for freeing it with DestroyIcon when you no longer need it.

因此您需要 PInvoke DestroyIcon并在函数结束时将您的 shinfo.hIcon 传递给它。

处理FromHandle创建的Icon不会破坏原来的句柄:

When using this method, you must dispose of the original icon by using the DestroyIcon method in the Win32 API to ensure that the resources are released.

关于c# - 方法在 3310 次成功后失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46976927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com