BinaryFormatter序列化和反序列化线程安全吗? [英] Are BinaryFormatter Serialize and Deserialize thread safe?

查看:88
本文介绍了BinaryFormatter序列化和反序列化线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用这可以改写为:

    private static BinaryFormatter formatter = new BinaryFormatter();

    public static T DeepClone<T>(this T a)
    {
        using(MemoryStream stream = new MemoryStream())
        {
            formatter.Serialize(stream, a);
            stream.Position = 0;
            return (T)formatter.Deserialize(stream);
        }
    }

那么要避免为每个调用构造(和GC'ing)新的BinaryFormatter?

So avoiding constructing (and GC'ing) a new BinaryFormatter for each call?

此代码路径非常频繁,因为它涉及我们的缓存层,我希望使其尽可能轻巧.

This code path is getting hit very frequently as it involves our caching layer and I would like to make it as lightweight as possible.

谢谢.

推荐答案

根据

任何公共静态(在Visual中共享 基本)此类型的成员是线程 安全的.任何实例成员都不是 保证是线程安全的.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

因此,您需要同步对Serialize/Deserialize方法的访问.

So you need to synchronize access to Serialize/Deserialize methods.

您是否通过每次创建本地序列化程序实例来识别特定的性能问题?

Have you identified particular performance issues by creating a local serializer instance every time?

更新:

我会信任MSDN,因为即使在某些情况下我们可以验证实例成员可能是线程安全的,这也不意味着在下一个Service Pack/更新/框架版本中,情况将继续如此.

I would trust MSDN because even if in some cases we can verify that instance members might be thread safe this doesn't mean that with the next service pack/update/framework version this will continue to be the case.

在BinaryFormatter构造函数中使用Reflector:

Looking with Reflector at BinaryFormatter constructor:

public BinaryFormatter()
{
    this.m_typeFormat = FormatterTypeStyle.TypesAlways;
    this.m_securityLevel = TypeFilterLevel.Full;
    this.m_surrogates = null;
    this.m_context = new StreamingContext(StreamingContextStates.All);
}

和StreamingContext构造函数:

And StreamingContext constructor:

public StreamingContext(StreamingContextStates state, object additional)
{
    this.m_state = state;
    this.m_additionalContext = additional;
}

坦率地说,分配6个属性(其中大多数是enums)应该非常快.恕我直言,大部分时间都将花费在Serialize/Deserialize方法中.

Quite frankly assigning 6 properties (most of which are enums) should be blindingly fast. IMHO most of the time would be spent in Serialize/Deserialize methods.

这篇关于BinaryFormatter序列化和反序列化线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆