【发布时间】:2015-05-19 15:14:32
【问题描述】:
我有一个线程安全的对象集合,例如 c# MemoryCache。众所周知,在此集合中添加、更新和删除项目等操作是安全的。但是,如果我通过引用更新集合中对象项的属性,首先,它是线程安全的吗?同步如何工作?是否会锁定每一行属性更新?
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();
非常感谢任何建议。
标签: c# multithreading synchronization thread-safety memorycache