There is a singleton service class ItemsDataSource: IItemsDataSource injected into many other classes (business domain classes)
These business domain classes are many and run asynchronously calling methods on that ItemsDataSource service.
public interface IItemsDataSource
{
Task<IEnumerable<string>> GetItemsAsync();
void SetSourceConfiguration(JToken src);
}
public class ItemsDataSource : IItemsDataSource
{
private JToken m_configuration;
public Task<IEnumerable<string>> GetItemsAsync()
{
// Use m_configuration to some items
}
public void SetSourceConfiguration(JToken config)
{
m_configuration = src;
}
}
When multiple classes that are using this service are running asynchronously (let's say on 2 threads T1 and T2), this is sometimes happening:
T1 calls SetSourceConfiguration(config1) then starts running GetItemsAsync() asynchronously.
T2 calls SetSourceConfiguration(config2) (m_configuration is now assigned with config2) before T1 is done running GetItemsAsync(). For that T1 uses config2 instead of config1 and unexpected behavior happens.
The questions:
1- The optimal fix I think is removing SetSourceConfiguration and passing the JToken config directly as parameter into GetItemsAsync, or locking the code in the business classes, or is there another better solution ?
2- Which design pattern violation caused this bug ? So It could be avoided in the first place.
3- What is the "technical" term for this bug ? Methods with Side Effects, Design pattern violation, etc. ?