【发布时间】:2016-06-10 15:15:31
【问题描述】:
假设我想允许并行执行一些代码,但需要其他代码等待所有这些操作完成。
让我们想象一个softlock 除了lock:
public static class MySimpleCache
{
private static readonly SynchronizedCollection<KeyValuePair<string, string>> Collection = new SynchronizedCollection<KeyValuePair<string, string>>();
public static string Get(string key, Func<string> getter)
{
// Allow parallel enumerations here,
// but force modifications to the collections to wait.
softlock(Collection.SyncRoot)
{
if (Collection.Any(kvp => kvp.Key == key))
{
return Collection.First(kvp => kvp.Key == key).Value;
}
}
var data = getter();
// Wait for previous soft-locks before modifying the collection and let subsequent softlocks wait
lock (Collection.SyncRoot)
{
Collection.Add(new KeyValuePair<string, string>(key, data));
}
return data;
}
}
C#/.NET 中是否有任何设计模式或语言/框架功能可以以一种简单可靠的方式实现这一点,还是必须从头开始实现这一点?
我目前仅限于 .NET 3.5,并且我最感兴趣的是概念问题,而不是其他可能解决示例本身的可能集合。
【问题讨论】:
-
听起来你需要ReaderWriterLockSlim,它可以从读取器锁开始,然后升级为写入器锁。
-
您的查找效率略低,您枚举了两次,您可以使用
var result = Collection.FirstOrDefault(kvp => kvp.Key == key); if(result != default(KeyValuePair<string, string>)) { return result.Value; }并且只查找一次。 -
@MatthewWatson 谢谢,看起来很合适,我会玩弄它。
-
哎呀!= 不起作用,但我正在写一个答案(使用 ReaderWriterLockSlim),它也有一个固定版本。
-
@ScottChamberlain 虽然那时我通常无法区分集合是否不包含该值,或者它包含的值是否为空。