.NET: Is JsonMediaTypeFormatter thread safe?

Viewed 590

The following code is slow because it generates dynamic serialization classes on every run:

var formatter = new JsonMediaTypeFormatter();
... // configure formatter

MyDocument value = new MyDocument();
HttpContent content = new ObjectContent<MyDocument>( value, formatter );
await httpClient.PutAsync( url, content );

Ideally I should cache the formatter value, however I'm using threads and the documentation says that instance members are not thread safe. This sounds like a design flaw or imprecise documentation, as the media type formatters can be used as ASP.NET content parsers (which are obviously thread-aware). Still it doesn't preclude the possibility that ASP.NET is using locks to avoid concurrent access.

Do you know any good source or indication that the JsonMediaTypeFormatter is actually thread-safe?

2 Answers

After I struggled to find what was causing performance issues in my code, I did a gist to prove where the performance issue was:

https://gist.github.com/anonymous/6c47b4138595e13f53c162d1c69ba0ed (A copy-n-paste made the gist use the static method two times in the last tuple).

The problem is in the code produced to read/write using DataContractJsonSerializer.

Also, I didn't find any official documentation regarding this issue neither in Mictosoft documentation nor in the internet.

Thanks for pointing us up in the right direction. I don't know if it's possible, but you could edit the question title and add performance issues in it.

Related