简体   繁体   中英

Is this static method thread-safe?

I have below classes:

public static class MetadataManager
{
    // assume that it is thread safe
    public static List<Field> FieldRegistry { get; set; }
}

public class Field
{
    public int ID { get; set; }
    public string Name { get; set; }
}



public static class FieldDataValidationManager
{
    public static bool Validate(int fieldID)
    {
        return MetadataManager.FieldRegistry.FirstOrDefault(f => f.ID == fieldID).ID > 1;
    }

    public static bool Validate(Field field)
    {
        return fieldID.ID > 1;
    }
}

Now, User1 and User2 is calling static method at the same time, is there any problem regarding concurrency?

FieldDataValidationManager.Validate(111) 

or User1 is executing FieldDataValidationManager.Validate(field1) and User2 is executing FieldDataValidationManager.Validate(field2)

Yes, your code is thread-safe, since your code is just reading from the list. Being static or not doesn't matter at all.

If there would be write actions on the List<T> , you would have possible concurrency problems. Then you should use ConcurrentBag<T> or other thread-safe collection types.

There is no concurrency problem as long as you don't change the content of the FieldRegistry list.
But you did not show where you fill that list. So if your actual code does insert or remove entries to that list while other threads are calling Validate there will be problems (a ConcurrentBag<T> as suggested by Patrick Hofman may be a good alternative for that).


But what are you actually trying to do here:

public static bool Validate(int fieldID)
{
    return MetadataManager.FieldRegistry.FirstOrDefault(f => f.ID == fieldID).ID > 1;
}

So it seems your fieldID is valid if there is already an entry with that ID and the ID is greater than 1 ?
OK, but your method will throw a NullReferenceException if the fieldID is not already contained in your list. So you better change that method to something like this:

public static bool Validate(int fieldID)
{        
    return 
        MetadataManager.FieldRegistry.Any(f => f.ID == fieldID) &&
        fieldID > 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM