【发布时间】:2012-02-19 18:55:55
【问题描述】:
我正在尝试建立一个订阅列表。举个例子吧:
出版商列表,每个都有一个杂志列表,每个都有一个订阅者列表
出版商 --> 杂志 --> 订阅者
在 C# 中的 Dictionary 中使用 Dictionary 是有意义的。在没有竞争条件的情况下添加/删除订阅者时,是否可以在不锁定整个结构的情况下执行此操作?
此外,C# 中的代码很快就会变得混乱,这让我觉得我没有走上正确的道路。有没有更简单的方法来做到这一点?下面是构造函数和订阅方法:
注意:代码使用 Source、Type、Subscriber 代替上面的名称
来源--->类型--->订阅者
public class SubscriptionCollection<SourceT, TypeT, SubscriberT>
{
// Race conditions here I'm sure! Not locking anything yet but should revisit at some point
ConcurrentDictionary<SourceT, ConcurrentDictionary<TypeT, ConcurrentDictionary<SubscriberT, SubscriptionInfo>>> SourceTypeSubs;
public SubscriptionCollection()
{
SourceTypeSubs = new ConcurrentDictionary<SourceT, ConcurrentDictionary<TypeT, ConcurrentDictionary<SubscriberT, SubscriptionInfo>>>();
}
public void Subscribe(SourceT sourceT, TypeT typeT, SubscriberT subT) {
ConcurrentDictionary<TypeT, ConcurrentDictionary<SubscriberT, SubscriptionInfo>> typesANDsubs;
if (SourceTypeSubs.TryGetValue(sourceT, out typesANDsubs))
{
ConcurrentDictionary<SubscriberT, SubscriptionInfo> subs;
if (typesANDsubs.TryGetValue(typeT, out subs))
{
SubscriptionInfo subInfo;
if (subs.TryGetValue(subT, out subInfo))
{
// Subscription already exists - do nothing
}
else
{
subs.TryAdd(subT, new SubscriptionInfo());
}
}
else
{
// This type does not exist - first add type, then subscription
var newType = new ConcurrentDictionary<SubscriberT, SubscriptionInfo>();
newType.TryAdd(subT, new SubscriptionInfo());
typesANDsubs.TryAdd(typeT, newType);
}
}
else
{
// this source does not exist - first add source, then type, then subscriptions
var newSource = new ConcurrentDictionary<TypeT, ConcurrentDictionary<SubscriberT, SubscriptionInfo>>();
var newType = new ConcurrentDictionary<SubscriberT, SubscriptionInfo>();
newType.TryAdd(subT, new SubscriptionInfo());
newSource.TryAdd(typeT, newType);
SourceTypeSubs.TryAdd(sourceT, newSource);
};
}
【问题讨论】:
-
这个问题是 C# 特有的,还是您正在寻找一种可以在任何地方使用的方法?
-
真的在任何地方.. 然后我可以将它改编为 C#
-
我之所以问,是因为如果问题是特定于 C# 的,那么您可以直接在 .Net 框架中使用类。
-
好吧,我想推荐
ConcurrentDictionary,但刚才注意到你已经在使用它了。
标签: c# data-structures collections thread-safety