[英]Thread Safe Publish Subscribe in .Net
我创建了一组简单的接口和一个类,使我可以在通用字典中发布项目的添加和删除。 订阅者在订阅时会收到整个列表,此后,他们只会获得更改。
尽管我的解决方案有效,但我正在寻找一些更标准,更便宜的产品。 你有什么建议吗?
关于我到目前为止发现的注释:
我一直在研究Microsoft的反应性扩展(Rx)。 根据乔恩·斯凯特(Jon Skeet)的文章“ LINQ to Rx:第二印象” [1],他说:“观察者一订阅,可观察对象就会立即按顺序发布所有内容(默认情况下,它在另一个线程上)。分别调用订阅使可观察的对象遍历整个序列多次。” 这听起来像是基本思路,但是我找不到任何具体示例,而且我不确定“ 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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.