我创建了一组简单的接口和一个类,允许我在通用字典中发布项目的添加和删除。订阅者在订阅时会收到整个列表,之后,他们只会得到更改。
虽然我的解决方案有效,但我正在寻找更标准的东西,而不是本土的东西。你有什么建议吗?
关于我到目前为止发现的内容的注释:
我一直在研究 Microsoft 的 Reactive Extensions (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/