[英]DropQueue mechanism for RX.net
我遇到了RX.net的反壓力問題,但找不到解決方案。 我有一個可觀察到的實時日志消息流。
var logObservable = /* Observable stream of log messages */
我想通過TCP接口公開該接口,該接口對從logObservable
發出的實時日志消息進行序列化,然后再通過網絡發送它們。 因此,我執行以下操作:
foreach (var message in logObservable.ToEnumerable())
{
// 1. Serialize message
// 2. Send it over the wire.
}
如果發生背壓情況(例如,另一端的客戶端暫停流.ToEnumerable()
,則.ToEnumerable()
會出現問題。 問題是.ToEnumerable()
緩存了導致大量內存使用的項目。 我正在尋找一種類似DropQueue
的機制,該機制僅緩沖最后10條消息,例如
var observableStream = logObservable.DropQueue(10).ToEnumerable();
這是解決此問題的正確方法嗎? 您知道實施這樣一種機制來避免可能出現的背壓問題嗎?
我的DropQueue
實現:
public static IEnumerable<TSource> ToDropQueue<TSource>(
this IObservable<TSource> source,
int queueSize,
Action backPressureNotification = null,
CancellationToken token = default(CancellationToken))
{
var queue = new BlockingCollection<TSource>(new ConcurrentQueue<TSource>(), queueSize);
var isBackPressureNotified = false;
var subscription = source.Subscribe(
item =>
{
var isBackPressure = queue.Count == queue.BoundedCapacity;
if (isBackPressure)
{
queue.Take(); // Dequeue an item to make space for the next one
// Fire back-pressure notification if defined
if (!isBackPressureNotified && backPressureNotification != null)
{
backPressureNotification();
isBackPressureNotified = true;
}
}
else
{
isBackPressureNotified = false;
}
queue.Add(item);
},
exception => queue.CompleteAdding(),
() => queue.CompleteAdding());
token.Register(() => { subscription.Dispose(); });
using (new CompositeDisposable(subscription, queue))
{
foreach (var item in queue.GetConsumingEnumerable())
{
yield return item;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.