jeudi 15 novembre 2018

Will lock prevent changes done via reflection

Assume a class SomeClass with private static field like this. The access to this field is synchronized using lock.

private static SomeClass _instance
private static object _sync = new object();

lock (_sync)
{
    if (_instance == null)
    {
        _instance = Create();
    }
    return _instance;   
}

When another code from different thread will try to set the value of this variable to e.g. null using reflection, will the lock prevent this and let the reflection call wait until the lock was released?

E.g. something like this:

Type type = typeof(SomeClass);
string fieldName = "_instance";
object value = null;
FieldInfo field = type.GetField(fieldName, true);
field.SetValue(null, value);





Aucun commentaire:

Enregistrer un commentaire