代码之家  ›  专栏  ›  技术社区  ›  Wayne Bloss

Net中的线程安全发布订阅

  •  0
  • Wayne Bloss  · 技术社区  · 15 年前

    我创建了一组简单的接口和一个类,允许我在通用字典中发布项的添加和删除。订阅者在订阅时接收整个列表,之后,他们只得到更改。

    虽然我的解决方案可行,但我正在寻找一种更标准、更不土生土长的解决方案。你有什么建议吗?

    我一直在研究微软的反应式扩展(Rx)。根据Jon Skeet的文章“LINQ to Rx:第二印象”[1],他说“只要一个观察者订阅了,被观察者就会发布序列中的所有内容(默认情况下,在不同的线程上)。单独调用Subscribe使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);
    }
    

    当然,我的泛型dictionary publisher类有以下方法:

    /// <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/

    1 回复  |  直到 7 年前
        1
  •  1
  •   VinayC    15 年前

    这不是一个真正的答案,但乏味的评论,所以把它放在这里。。。 不知道你为什么要看 pattern 如果您没有找到任何替代方案,并决定与您的自定义解决方案,然后您可以参考这个 artcile