【问题标题】:Thread Safe Publish Subscribe in .Net.Net 中的线程安全发布订阅
【发布时间】: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/

【问题讨论】:

标签: c# .net thread-safety publish-subscribe


【解决方案1】:

这不是一个真正的答案,但放入 cmets 很乏味,所以把它放在这里...... 当您的自定义解决方案易于构建并且可以工作时,不确定您为什么要寻找开箱即用的标准解决方案? 事件是实现发布者-订阅者模型的最简单(和标准)的方法,但它们不是线程安全的,并且还存在订阅者和发布者之间的紧密耦合。 MS 模式和实践小组已经发布了基于 WCF 的pattern,但我认为您正在寻找一种快速的进程内代码。类似地,许多其他标准发布-订阅解决方案将针对应用程序集成 (ESB)。 如果您没有找到任何替代方案并决定使用您的自定义解决方案,那么您可以参考此artcile,它描述了实现此设计模式的问题。

【讨论】:

  • 感谢您的回答。如果没有必要,我尽量不要重新发明轮子。也许我会写一篇关于我的实现的博客文章。然后,我肯定会有很多人告诉我它有什么问题!
  • 我会给你答案,因为你的评论对我有帮助。我把我正在使用的代码放在这里code.google.com/p/waynescode/source/browse/#svn/trunk/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多