i have the following static class with generic methods and i'm wondering if it's safe to use it from different threads and with different objects? i'm not sure how this works below the covers so an explanation of would help
public static class Serialization { public static byte[] Serialize<T>(T obj) { using (var ms = new MemoryStream()) { Serializer.SerializeWithLengthPrefix<T>(ms, obj, PrefixStyle.Base128); return ms.ToArray(); } } public static T DeSerialize<T>(byte[] bytes) { using (var ms = new MemoryStream(bytes)) { return Serializer.DeserializeWithLengthPrefix<T>(ms, PrefixStyle.Base128); } } }
This question is related to
c#
generics
thread-safety
protobuf-net
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
Source: Stackoverflow.com