问题描述
最近,我在代码中发现了一个使用Reactive Extensions的小错误.我正在订阅Timer,但从未取消我的订阅.这导致内存泄漏.
Recently I noticed a small bug in my code which uses Reactive Extensions. I was subscribing to Timer but I never disposed my subscription. This resulted in a memory leak.
我创建了摘录,突出了这种危险:
I created snippet which highlights this danger:
while (true)
{
Observable.Timer(TimeSpan.Zero, TimeSpan.FromMinutes(1)).Subscribe(Console.WriteLine);
}
这是正常行为吗?
当订阅者与应用程序的其余部分失去连接时,调度程序不应该对计时器保持弱引用以使其被垃圾回收吗?
Shouldn't scheduler hold weak reference to timer to get it garbage collected when subscribers lost connection with the rest of the app?
推荐答案
这是正常现象,并且是功能.
This is normal, and is a feature.
Subscribe()的语义将永远被监听,或者直到Disposed()或OnCompleted()或OnError()成为最先出现.
The semantics for Subscribe() are listen forever, or until Disposed() or OnCompleted(), or OnError(), which ever comes first.
这篇关于Observable.Timer()会导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!