1

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);
        }
    }
}
RomSteady
  • 398
  • 2
  • 13
kogilvie
  • 145
  • 2
  • 9
  • 1
    Looks fine to me. Are you having a specific problem? – klugerama Dec 31 '13 at 22:12
  • 4
    Nothing obviously thread-unsafe about it. You'll have a problem if another thread modifies *obj* while you serialize it, same with *bytes* but a lot less likely. – Hans Passant Dec 31 '13 at 22:13
  • Check [answer here](http://stackoverflow.com/questions/1090650/are-static-methods-thread-safe) for longer explanation. Short is: Static methods are thread-safe by default as long as they are not committing some multi-thread voodoo. – PTwr Dec 31 '13 at 22:14
  • 2
    Take a look on protobuf docs, if `Serializer.SerializeWithLengthPrefix` and `Serializer.DeserializeWithLengthPrefix` are thread safe then - Yes, your code is thread safe. Note: the static methods should be thread safe, by guideline, but check :) – GSerjo Dec 31 '13 at 22:17
  • 1
    @PTwr more correctly: static methods ***should*** be thread-safe, ***by convention***. There is nothing default or automatic about it though. But in this case: yes they are thread safe. – Marc Gravell Dec 31 '13 at 22:33

2 Answers2

4

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.

Sam Plus Plus
  • 4,381
  • 2
  • 21
  • 43
nvoigt
  • 75,013
  • 26
  • 93
  • 142
1

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900