Thread safety and System.Text.Encoding in C#

余生长醉 提交于 2019-12-19 12:24:40

问题


Is it safe to use the same Encoding object from different threads?

By "using" I mean, calling Encoding.GetString(), Encoding.GetBytes() and write some XML with an XmlWriter (created by something like XmlWriter.Create(myStream, new XmlWriterSettings() { Encoding = myEncoding }).

The msdn site states that "Any instance members are not guaranteed to be thread safe".

So, how can I safely write two XML documents concurrently? (thank you!!)


回答1:


Yes, it should be safe to use the same Encoding object, as it's designed to be stateless - whereas Encoder and Decoder are stateful, maintaining incomplete characters etc if necessary. I suppose you could write a stateful Encoding class, but it would be a really bad idea. As far as I'm aware, all of the built-in encoding implementations are stateless and thread-safe.

For example, the Encoding.UTF8, Encoding.ASCII etc properties are singletons.



来源:https://stackoverflow.com/questions/3024384/thread-safety-and-system-text-encoding-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!