【问题标题】:Is the X509Certificate2 class thread-safe?X509Certificate2 类是线程安全的吗?
【发布时间】:2021-05-23 10:37:49
【问题描述】:

告诉我X509Certificate2 类是线程安全的吗?有条件的,我可以这样使用:

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 
    }
}

避免每次都创建实例,从而减少GC的负载?

【问题讨论】:

标签: c# thread-safety


【解决方案1】:

不保证该对象是线程安全的,因为它有一个“句柄”方法,它本身就是一个包装器并使用较低级别的函数。

如果您使用的是 .NET 4.6+,则应将对象包装在 using 语句中以正确处理它,否则您会发现将小证书复制到磁盘到多个位置时会出现问题。

如果您不确定,请使用“lock”关键字和“使用”语句。

【讨论】:

    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 2012-11-22
    • 2016-05-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多