【发布时间】:2010-08-17 03:15:01
【问题描述】:
我创建了一组简单的接口和一个类,允许我在通用字典中发布项目的添加和删除。订阅者在订阅时会收到整个列表,之后,他们只会获得更改。
虽然我的解决方案有效,但我正在寻找更标准的东西,而不是本土的东西。你有什么建议吗?
关于我目前发现的内容的注释:
我一直在研究 Microsoft 的反应式扩展 (Rx)。根据 Jon Skeet 的文章“LINQ to Rx:第二印象”[1],他说“一旦观察者订阅,observable 就会将序列中的所有内容发布给它(默认情况下在不同的线程上)。单独调用订阅让 observable 对序列进行多次迭代。”这听起来像是基本思想,但我找不到任何具体的例子,而且我还不确定“Subject”或“AsyncSubject”的线程安全性。
关于我自己的解决方案的说明:
交付给订阅者的结构如下所示:
/// <summary>
/// Interface for a set of changes that are being published.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TItem"></typeparam>
public interface IPublication<TKey, TItem>
{
/// <summary>
/// Version of the list.
/// </summary>
long Version { get; }
/// <summary>
/// Items that were added or updated.
/// </summary>
IEnumerable<TItem> ChangedItems { get; }
/// <summary>
/// Keys to items that were removed.
/// </summary>
IEnumerable<TKey> RemovedKeys { get; }
}
订阅者自己必须实现这个接口:
/// <summary>
/// Interface for a subscriber that will receive IPublication{TKey, TItem} deliveries from a publisher.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TItem"></typeparam>
public interface ISubscribe<TKey, TItem>
{
void Deliver(IPublication<TKey, TItem> pub);
}
当然我的通用字典发布者类有这个方法:
/// <summary>
/// Adds the give subscriber to the list of subscribers and immediately publishes the
/// dictionary contents to the new subscriber. The return value may be disposed when
/// the subscriber wishes to terminate it's subscription.
/// </summary>
/// <param name="subscriber"></param>
/// <returns></returns>
public IDisposable Subscribe(ISubscribe<TKey, TItem> subscriber);
[1] https://codeblog.jonskeet.uk/2010/01/19/linq-to-rx-second-impressions/
【问题讨论】:
-
您绝对应该深入研究 Rx,并考虑在 DevLabs Rx 论坛上提问:social.msdn.microsoft.com/Forums/en-US/rx/threads
标签: c# .net thread-safety publish-subscribe