[英]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.