我希望以下LINQPad代码能够在1秒内完成执行.但是在我的机器上一直需要15秒才能完成.我在这里缺少什么 - 这只是RX开销吗?
int count = 0;
ManualResetEvent done = new ManualResetEvent(false);
Observable.Interval(TimeSpan.FromMilliseconds(1))
.Take(1000)
.Subscribe((next) => count++, () => done.Set());
done.WaitOne();
count.Dump("Items observed");
Run Code Online (Sandbox Code Playgroud)
您所看到的不是Rx的开销 - 只是.NET计时器的分辨率是15毫秒.虽然您指定1ms间隔,但您将获得15ms.这是15秒的来源 - 1000 x 15ms = 15s.
相反,在我的笔记本电脑上,以下输出0表示已用时间:
var subject = new Subject<Unit>();
var stopwatch = new Stopwatch();
subject.Subscribe(_ => {}, () => {
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds); });
stopwatch.Start();
for(int i = 0; i<1000; i++)
{
subject.OnNext(Unit.Default);
}
subject.OnCompleted();
Run Code Online (Sandbox Code Playgroud)