Lin
Lin

Reputation: 663

Thread safety of Object Instances in an .Net

I want to keep some set of objects in static dictionary (to work as a factory with objects in memory) and avoid instantiation at every time an action is requested. The objects in the factory (objects in memory) do not have any state and the dependencies are passed from outside. I wanted to double check there is No thread safety issues involved here , the sample code is as below:

public interface IDataValidator
{
    bool Validate(long identifier);
}

public class ValidatorLocator
{
    private static readonly Dictionary<string, IDataValidator> DataValidators = new Dictionary<string, IDataValidator>
                                                                          {
                                                                            { "binary",  new BinaryDataValidator()},
                                                                              { "hex",  new HexDataValidator()}
                                                                          };
    public static IDataValidator GetDataValidator(string valType)
    {
        return DataValidators.ContainsKey(valType) ? DataValidators[valType] : null;
    }
}

public class HexDataValidator : IDataValidator
{
    public bool Validate(long identifier)
    {
        //evaluate business logic
        return true;
    }
}

public class BinaryDataValidator : IDataValidator
{
    public bool Validate(long identifier)
    {
        //evaluate business logic
        return true;
    }
}

Please indicate if I am heading for any disaster and any quick guidance is much appreciated. A bit skeptic about threads ( How does this look from an ASP.Net request thread perspective?)

Upvotes: 0

Views: 73

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100610

Your sample code is thread safe:

  • your dictionary is not modified after initial creation - concurrent Dictionary reads is thread safe and don't need synchronization if there is no write operations of any kind on it.
  • your objects have no state - thread safe.

Upvotes: 2

Related Questions