The other day a customer of mine was experiencing big delays when making this kind of calls to X509Certificate2 constructor:
X509Certificate2 cert = new X509Certificate2(byteArray);
Sometimes this process was almost instant, sometimes it took up to 2 minutes to create the object!!! During the reproduction of the issue, CPU usage was very high.
I debugged the issue and found out that it is related to this:
X509Certificate creates temporary files which are never deleted
When calling this specific X509Certificate2 constructor, .NET ends up calling CryptQueryObject API behind the scenes. This API will make calls to GetTempFileName API, and the delay is happening in there. This is a known issue on a couple Window versions, and fortunately there is a fix for it: On a Windows Server 2003-based or Windows Server 2008-based client computer, the system does not delete a temporary file that is created when an application calls the "CryptQueryObject" functionMy customer had a few hundred temp files more than 65,000. Having so many files seriously affects the performance of GetTempFileName, which explains the high CPU usage.
After deleting the files, performance was as expected. Still, we need to install the fix so those files are deleted when they should.
Alex (Alejandro Campos Magencio)
I just uncovered this same issue after some tough debugging. Glad there is a hotfix for it!