Are BinaryFormatter Serialize and Deserialize thread safe?

c#, multithreading, serialization, thread-safety

Solution

According to MSDN:

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

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

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

UPDATE:

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.

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

And StreamingContext constructor:

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

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.

Problem

Referencing this answer to a question. Can this be rewritten as: ``` 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); } } ``` 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. Thanks.

Original source

Related problems