Do I need to care about thread safety when read/writing to items inside a List
used inside a singleton.
If so, do I need to lock the getter/setter of Foo.Value
or FooManager.FooList
?
I know that reading and adding items to a List
is not thread-safe, but I'm unsure if this also applies to my code.
Example code:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
var manager = new FooManager();
manager.FooList.Add(new Foo());
manager.FooList.Add(new Foo());
manager.FooList.Add(new Foo());
var updater = new FooUpdater(manager);
updater.UpdateAsync();
}
}
public class FooManager // Singleton
{
public List<Foo> FooList {get;set;}
public FooManager()
{
FooList = new List<Foo>();
}
}
public class Foo
{
public string Value {get; set;}
public async Task UpdateValue(string value)
{
await Task.Delay(10000);
Value = value;
}
}
public class FooUpdater // HostedService
{
private readonly FooManager _foomanager;
public FooUpdater(FooManager foomanager)
{
_foomanager = foomanager;
}
public async Task UpdateAsync()
{
while(true)
{
foreach(var foo in _foomanager.FooList)
{
await foo.UpdateValue("AAA");
}
}
}
}
public class FooController // Api Controller
{
private readonly FooManager _fooManager;
public FooController(FooManager foomanager)
{
_fooManager = foomanager;
}
// ...
// Read or write to foomanager.FooList items value
}