【发布时间】:2017-04-01 10:14:48
【问题描述】:
假设如下情况:
public HashTable map = new HashTable();
public void Cache(String fileName) {
if (!map.ContainsKey(fileName))
{
map.Add(fileName, new Object());
_Cache(fileName);
}
}
}
private void _Cache(String fileName) {
lock (map[fileName])
{
if (File Already Cached)
return;
else {
cache file
}
}
}
当有以下消费者时:
Task.Run(()=> {
Cache("A");
});
Task.Run(()=> {
Cache("A");
});
Cache 方法是否有可能以任何方式抛出 Duplicate key 异常,这意味着两个任务都会命中 map.add 方法并尝试添加相同的键??
编辑:
使用下面的数据结构能解决这个并发问题吗?
public class HashMap<Key, Value>
{
private HashSet<Key> Keys = new HashSet<Key>();
private List<Value> Values = new List<Value>();
public int Count => Keys.Count;
public Boolean Add(Key key, Value value) {
int oldCount = Keys.Count;
Keys.Add(key);
if (oldCount != Keys.Count) {
Values.Add(value);
return true;
}
return false;
}
}
【问题讨论】:
标签: c# multithreading locking task