Is the JsonSerializerSettings thread safe?

If I use the same settings across my project, can I instantiate a single static copy of my JsonSerializerSettings and use that throughout?

For example :

private static readonly JsonSerializerSettings settings = new JsonSerializerSettings {
    Formatting              = Formatting.Indented,
    TypeNameHandling        = TypeNameHandling.None,
    DateFormatHandling      = DateFormatHandling.IsoDateFormat,
    TypeNameAssemblyFormat  = FormatterAssemblyStyle.Simple
};

public static string ToJSONString(this Object source) {
    return JsonConvert.SerializeObject(source, settings);
}   

So, am i thread dangerous?


The following conversation happened on twitter, @JamesNK being the author of JSON.net: https://twitter.com/jonathan_oliver/status/332227095616966656

From: Jonathan Oliver ‏@jonathan_oliver To: @JamesNK

Are the static JsonConvert.DeserializeObject methods thread safe? Getting some strange errors using 5.0.4 and 5.0.5.

Response:

James Newton-King ♔ ‏@JamesNK 8 May 2013 @jonathan_oliver

Yes. Create an issue on GitHub if they're not

Response:

Jonathan Oliver ‏@jonathan_oliver 9 May 2013

@JamesNK It turns out a ContractResolver attached to a static JsonSerializerSettings object I used with JsonConvert wasn't thread safe.

I do not see that a bug was ever filed, but this does hint that the design of them is supposed to be thread safe, but there maybe implementation specific ways to ruin that or it might not be as a whole.


Since you say you don't mutate JsonSerializerSettings there is no need to worry about thread safety. Thread race can happen only when modifying the shared data in another thread but that is not the case here.

I suggest you to read this article, in the end you should have a good understanding of threads, thread safety etc.

Also Thread safety is a more general term, you need to be more precise what you meant by that. Refer What is this thing you call "thread safe"? for more info.

链接地址: http://www.djcxy.com/p/78682.html

上一篇: Web API中基于上下文的REST超媒体URI更改(HATEOAS)

下一篇: JsonSerializerSettings线程安全吗?