Static method is thread-safe if new instances are returned allways it gets called?

159 Views Asked by At

I have the following classes:

public class SesionPasoProxy
{
    private static EntitySerializer _serializer = EntitySerializer.Create();

    public static string Obtener(Guid idSesion, int orden)
    {
        SesionPaso item = new SesionPaso();
        item.Orden = orden;
        item.IdSesion = idSesion;
        return _serializer.ToXml(item);

    }        
}


 public class EntitySerializer
 {
      private EntitySerializer(){}  
      public static EntitySerializer Create()
      {
         return EntitySerializer.Create("Test");
      }

       public static EntitySerializer Create(string serializationContextName)
       {
            EntitySerializer  instance = new EntitySerializer();
            instance.Name = serializationContextName;
            return instance;
       }
       public ToXml(SesionPaso x){ return x.toString();}
}

Is that code thread-safe? SessionPasoProxy is used inside a ASP.NET WebForms aspx page. So it can get called concurrently. As you see EntitySerializer is static but is returns new instances (not Singleton) What do you think? My unit testing is showing is thread.safe, but i am not sure at all.

Many thanks

1

There are 1 best solutions below

4
On BEST ANSWER

In general static methods aren't more or less thread safe than instance methods. But if they only use local variables instead of fields it's likely that they are thread-safe(of course it depends on the methods used).

In your case Create is thread-safe because it always returns a new instance and no other (static) field was used which could be accessed from different threads at the same time.

But one thing: you should make EntitySerializer.ToXml static too instead of using the same instance in Obtener. It doesn't need to be an instance method:

public static string ToXml(SesionPaso x){ return x.toString();}

Then you don't need the static field _serializer(at least not for this):

public static string Obtener(Guid idSesion, int orden)
{
    SesionPaso item = new SesionPaso();
    item.Orden = orden;
    item.IdSesion = idSesion;
    return EntitySerializer.ToXml(item);
}