JsonSerializer is in System.Text.Json. The reader, the writer, and the document types are single-threaded objects that you create for each operation. This page says which is which.
Summary
XmlSerializer and XmlSerializerOptions
Call the staticXmlSerializer methods from any thread. Create one XmlSerializerOptions instance, keep it in a static field or register it as a singleton, and pass it to every call. The converters and type metadata that the options resolve are cached on the instance, so a new instance for each call repeats that work. This is the same guidance as for JsonSerializerOptions.
- The options keep resolved converters and type metadata in concurrent dictionaries, and the metadata for a type is built under a lock, so two threads that ask for the same type for the first time get the same instance.
- For a synchronous call, the serializer reuses one
Utf8XmlWriterand one buffer for each thread, held in thread-static fields that no other thread sees. A call that crosses anawait, such asSerializeAsyncEnumerable, takes a spare writer with an atomic exchange, so no two calls hold the same writer. - The state that reading an object needs is taken with an atomic exchange. A second thread that reads the same type at the same moment gets its own.
Options become read-only on first use
AnXmlSerializerOptions instance can be changed until it is used. The first call that serializes or deserializes with it, or that asks it for type metadata with GetTypeInfo or TryGetTypeInfo, makes it read-only. You can also call MakeReadOnly yourself. From then on, every property setter and both lists (Converters and TypeInfoResolverChain) throw InvalidOperationException. IsReadOnly tells you which state the instance is in.
This “freezing” is what makes sharing safe: the cached metadata was built from the settings, so the settings can’t change underneath it.
To get options that differ from a read-only instance, copy it. The copy can be changed, and it shares no cached state with the original.
Source-generated contexts
A context that derives fromXmlSerializerContext is bound to one options instance and can be shared in the same way. The generated Default property is a static instance made for that purpose.
A generated context creates the metadata for each type the first time its property is read, and stores it in a field without a lock. If two threads read the property for the first time at the same moment, each can build the metadata, and one of the two is kept. Both describe the same type with the same options, so either one gives the same result.
Passing options to a context’s constructor makes the context the TypeInfoResolver of those options. Do that before the options are used, because the constructor throws InvalidOperationException for read-only options.
Converters and naming policies
The serializer creates or takes one converter instance for each type and options instance, and calls it from every thread that serializes that type. A naming policy is called the same way.- Don’t keep state for one call in a field of a converter or a naming policy. Use local variables.
- A converter that caches something must synchronize the cache itself.
- A converter that calls
XmlSerializeragain for a nested value is safe. The nested call gets its own writer.
Utf8XmlWriter
AUtf8XmlWriter isn’t thread-safe. It holds the open elements, the namespace scopes, and unflushed bytes, and nothing in it is synchronized. Use one writer from one thread at a time, and don’t share the IBufferWriter<byte> or Stream it writes to with another writer.
You can reuse a writer for another document on another thread once the first use is finished: call Reset with the new destination. What you can’t do is call it from two threads at once. After Dispose, the write methods throw ObjectDisposedException.
See Use Utf8XmlWriter.
Utf8XmlReader
Utf8XmlReader is a ref struct, like Utf8JsonReader. The compiler doesn’t let you store it in a field of a class, capture it in a lambda, or keep it across an await, so it can’t be shared between threads.
To continue reading on another thread or after an await, save reader.CurrentState, which is an XmlReaderState value, and create a new reader over the next block of input with that state. The input buffer must not change while a reader is over it. See Use Utf8XmlReader.
XmlDocument and XmlElement
AnXmlDocument is read-only after Parse returns, and an XmlElement is a small value that points into its document. Reading a document doesn’t write to it, so several threads can read the same document.
Dispose is the exception. It returns the document’s buffers to the shared array pool, and it isn’t synchronized with readers.
- Don’t call
Disposewhile another thread might still be reading the document or anyXmlElementfrom it. A thread that reads duringDisposecan see a buffer that the pool has already given to someone else. - After
Disposehas finished, the document and everyXmlElementfrom it throwObjectDisposedException. - Give the document one owner that disposes it when all readers are done. To keep a part of a document for longer, copy it out first with
XmlElement.CloneNodeor by reading the values you need.
XmlNode
The node types inCloudNimble.Text.Xml.Nodes (XmlNode, XmlElementNode, XmlAttributeNode, and the others) form a mutable tree with no locking. Treat a tree like a JsonNode tree:
- A tree that no thread is changing can be read from several threads at once. A tree from
XmlNode.Parsebuilds each element’s attributes and children the first time they are read. That is safe from several threads: each element’s lists are put in place whole, and threads that read the same element at the same moment all get the same nodes. Reading includesToString,WriteTo, andDeepClone. - While any thread adds, removes, or changes a node, no other thread can use that tree, not even to read it. Use your own lock.
- A
foreachoverChildrenorAttributesthrows anInvalidOperationExceptionwhen the list changes under it. That catches a loop that changes its own list. It isn’t a substitute for a lock.
See also
Configure serializer options
Create, copy, and reuse XmlSerializerOptions.
Use source generation
Create and share an XmlSerializerContext.
Security
Limits and guidance for untrusted input.
Native AOT
Serialize without reflection.