Tag: 高阶函数

锁定一个实习的字符串?

更新:如果此方法不是线程安全的,这是可以接受的,但我有兴趣学习如何使其线程安全。 另外,如果可以避免,我不想为所有key锁定单个对象。 原始问题:假设我想编写一个更高阶的函数,它接受一个键和一个函数,并检查一个对象是否已使用给定的密钥进行缓存。 如果是,则返回缓存的值。 否则,运行给定的函数并缓存并返回结果。 这是我的代码的简化版本: public static T CheckCache(string key, Func fn, DateTime expires) { object cache = HttpContext.Current.Cache.Get(key); //clearly not thread safe, two threads could both evaluate the below condition as true //what can I lock on since the value of “key” may not be known at compile time? if (cache == null) […]