ฉันมีคอลเลกชันอ็อบเจ็กต์เธรดที่ปลอดภัย เช่น c# MemoryCache ดังที่เราทราบ การดำเนินการต่างๆ เช่น การเพิ่ม การอัปเดต และการลบรายการในคอลเลกชันนี้ปลอดภัย แต่หากฉันอัปเดตคุณสมบัติของรายการอ็อบเจ็กต์ในคอลเลกชันผ่าน Reference ประการแรก มันจะปลอดภัยสำหรับเธรดหรือไม่ การซิงโครไนซ์ทำงานอย่างไร? มันจะล็อคการอัพเดตคุณสมบัติแต่ละบรรทัดหรือไม่?
class MyClass
{
public int Val1 { get; set; }
public int Val2 { get; set; }
}
class Program
{
public static MemoryCache MyCache = new MemoryCache("test");
static void Main(string[] args)
{
MyCache.Add("1", new MyClass() {Val1 = 0, Val2 = 0}, new CacheItemPolicy());
new Thread(() => {
MyClass item = (MyClass)MyCache["1"];
for (int i = 0; i < 100000; i++)
{
item.Val1 = item.Val1 + i;
}
}).Start();
new Thread(() =>
{
MyClass item = (MyClass)MyCache["1"];
for (int i = 100000; i < 200000; i++)
{
item.Val1 = item.Val1 + i;
}
}).Start();
คำแนะนำใด ๆ ที่ชื่นชมจริงๆ