我正在使用.NET 3.5。
创建对 X509Certificate 的引用时,我遇到了内存泄漏。我正在使用 ANTS 探查器来分析结果,并且私有字节正在增加,而堆中的字节保持静态(表明这是由于非托管代码导致的内存泄漏)。
我正在使用 CRYPT32 dll 来管理证书。我打开对证书存储的引用以获取作为内部指针 (intptr) 的存储句柄。然后我使用这个存储处理程序在存储中查找证书(保存在本地)。获得证书后,我关闭证书存储并将证书返回给调用程序。我在 certclosestore 中使用标志 0,它在调用关闭存储后保持打开的资源打开。我相信这是导致内存泄漏的原因,因为它在这里提到:http: //msdn.microsoft.com/en-us/library/ms937035.aspx
但是,当我将关闭标志更改为:
CertCloseStore(storeHandle, 2)
这应该释放分配的资源。然而,它只会导致服务爆炸。
该应用程序的工作原理是验证证书等。唯一的问题是内存使用量正在缓慢上升,并且需要每周左右重新启动服务。任何想法或想法将不胜感激。
public static X509Certificate CreateFromRegistry(string certificateIdent)
{
X509Certificate certificate = null;
IntPtr storeHandle = CertificateStore.CertOpenStore(CERT_STORE_PROV_SYSTEM,
0, 0,CERT_SYSTEM_STORE_LOCAL_MACHINE, "MY");;
certificate = new X509Certificate(CertificateStore.
FindCertInStore(certificateIdent, storeHandle));
CertificateStore.CertCloseStore(storeHandle, 0);
return certificate;
}
public class CertificateStore
{
const int CERT_STORE_PROV_SYSTEM = 10;
private static int CERT_SYSTEM_STORE_LOCAL_MACHINE = (2 << 16);
const uint PKCS_7_ASN_ENCODING = 0x00010000;
const uint X509_ASN_ENCODING = 0x00000001;
const uint CERT_FIND_SUBJECT_STR = 0x00080007;
const uint CERT_FIND_ISSUER_STR = 0x00080004;
static uint MY_ENCODING_TYPE = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;
[DllImport("CRYPT32", EntryPoint = "CertOpenStore",
CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CertOpenStore(
int storeProvider, int encodingType,
int hcryptProv, int flags, string pvPara);
[DllImport("CRYPT32", EntryPoint = "CertCloseStore",
CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertCloseStore(
IntPtr storeProvider,
int flags);
}
public static X509Certificate FindCertInStore
(string trustedRootIssuerName, IntPtr storeHandle)
{
IntPtr hCertCntxt;
X509Certificate theActualCertificate = null;
if (storeHandle != IntPtr.Zero)
{
hCertCntxt = CertFindCertificateInStore(
storeHandle,
MY_ENCODING_TYPE,
0,
CERT_FIND_ISSUER_STR,
trustedRootIssuerName,
IntPtr.Zero);
if (hCertCntxt != IntPtr.Zero)
{
theActualCertificate = new X509Certificate(hCertCntxt);
}
}
return theActualCertificate;
}