我有以下异步队列处理路由。
var commandQueue = new BlockingCollection<MyCommand>();
commandQueue
.GetConsumingEnumerable()
.ToObservable(new LimitedConcurrencyLevelTaskPoolScheduler(5))
.Subscribe(c =>
{
try
{
ProcessCommand(c);
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
}
);
在一种特定情况下(当我要获取一些数据时),我需要确保我的 commandQueue 为空,然后再出去获取数据。此操作预计将同步发生。基本上,我想做类似的事情
public void GetData()
{
commandQueue.WaitForEmpty();
// could potentially be expressed:
// while (commandQueue.Count > 0) Thread.Sleep(10);
return GoGetTheData()
}
我意识到在理想情况下,所有调用者都将“GetData”异步......但有时它必须以同步方式发生......所以我需要等待命令队列为空以确保一致性和我的数据的最新性。
我知道如何使用 ManualResetEvent 很容易地做到这一点……但我想知道 System.Reactive/TPL 是否有简单的方法。
谢谢。