0

Tell me the X509Certificate2 class is thread-safe? Conditionally, I can use it in this way:

public class MyClass 
{
    // example
    private static readonly X509Certificate2 staticCertInstance = 
        new X509Certificate2("cert.pfx");

    // the method can be called from different threads
    public void Execute() 
    {
        // use staticCertInstance 
    }
}

To avoid creating an instance every time, thereby reducing the load on the GC ?

jamesnet214
  • 1,044
  • 13
  • 21
Vas Mil
  • 605
  • 1
  • 8
  • 21
  • You have a constant that is read only so once it is created it is thread safe. – jdweng May 23 '21 at 10:43
  • 1
    Does this answer your question? [Thread safety on readonly static field initialisation](https://stackoverflow.com/questions/12159698/thread-safety-on-readonly-static-field-initialisation) – Akshay G May 23 '21 at 10:51
  • None of its members are marked in the documentation as being thread-safe, so it may not be. If you want to reduce GC load, you could try creating an [ObjectPool](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.objectpool.objectpool-1?view=dotnet-plat-ext-5.0) of them? – yaakov May 23 '21 at 10:57

1 Answers1

1

This object is not guaranteed to be thread safe since it has a "handle" method being itself a wrapper and using lower level functions.

If you are using .NET 4.6+ you should wrap the object inside a using statement to dispose it correctly or you can find problems copying to disk small certificates into several locations.

So use "lock" keyword if you are unsure and "using" statement.

Juanma Feliu
  • 1,298
  • 4
  • 16