如何在需要的 Rx .NET / Dispose 中使用简单的超时?
使用 Rx .NET 在 3 秒后引发火灾并忘记回调的最简单方法是什么。我注意到这有效,但我必须处理它还是什么?我不知道。
Observable.Timer(TimeSpan.FromSeconds(3)).Subscribe(x => Console.WriteLine("Fired"));
What is the most simple way to raise a fire and forget callback after 3 seconds with Rx .NET. I noticed this works, but do I have to dispose it or something? Im not sure.
Observable.Timer(TimeSpan.FromSeconds(3)).Subscribe(x => Console.WriteLine("Fired"));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就是这样,如果可以的话,我会将您的问题标记为答案;)。
关于处置,如果出现以下情况,您通常需要处置订阅:
您的示例不是其中之一,因此不必担心取消订阅。
This is it, I would mark your question as an answer if I could ;).
Regarding disposal, you usually need to dispose the subscription if:
Your sample is not one of these, so don't worry about unsubscribing.
只是为了好玩,这里有另一种替代方案,它使用 Rx,但将调度程序放在前面和中心,并省略订阅业务和 Action 上不必要的参数。和以前一样,您可以使用返回的
IDisposable
来取消操作:Just for kicks, here's another alternative that uses Rx but puts the scheduler front and centre and omits the subscription business and the unnecessary argument on the Action. As before you could use the returned
IDisposable
to cancel the action.:只是好奇,但你的问题说“超时”,而不是“计时器”。您所拥有的是在给定时间发生的事件,而不是等待给定时间后放弃的事件。虽然您似乎对答案感到满意,但我想我应该检查一下是否清楚。
要执行后面的操作,您可以将 .Timeout(Timespan) 添加到可观察序列中。正如 James World 所提到的,这里有一个调度程序在隐式地发挥作用。当您保持调度程序隐式时,您会发现单元测试很痛苦。理想情况下,您应该为您使用的计时器/间隔/超时方法提供您想要使用的调度程序。
Just curious, but your question says 'timeout', not 'timer'. What you have is an event that occurs at the given time, not a wait on an event gives up after a given time. While it seems you are happy with the answer, I thought I would check for clarity.
To do the later, you can add a .Timeout(Timespan) to an observable sequence. As James World has mentioned, there is a Scheduler at play here implicitly. While you keep the Scheduler implicit you will find unit-testing a pain. Ideally you should provide the Scheduler you want to use to the Timer/Interval/Timeout method you use.