在单个并发执行限制下,使用Rx运行定期任务的好方法是什么?

编程入门 行业动态 更新时间:2024-10-26 06:30:28
本文介绍了在单个并发执行限制下,使用Rx运行定期任务的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要运行定期任务,但要限制在任何给定时间最多只能运行一种方法的执行.

I want to run periodic tasks in with a restriction that at most only one execution of a method is running at any given time.

我正在尝试使用Rx,但是我不确定如何强加一次并发限制.

I was experimenting with Rx, but I am not sure how to impose at most once concurrency restriction.

var timer = Observable.Interval(TimeSpan.FromMilliseconds(100)); timer.Subscribe(tick => DoSomething());

此外,如果任务仍在运行,我希望随后的时间表过去.即我不希望任务排队并导致问题.

Additionally, if a task is still running, I want the subsequent schedule to elapse. i.e I don't want the tasks to queue up and cause problems.

我有2个这样的任务要定期执行.当前正在执行的任务是同步的.但是,如果有必要,我可以使它们异步.

I have 2 such tasks to execute periodically. The tasks being executed is currently synchronous. But, I could make them async if there is a necessity.

推荐答案

您应该已经按原样测试了代码,因为这正是Rx已经强加的.

You should have tested your code as is because this is exactly what Rx imposes already.

尝试一下作为测试:

void Main() { var timer = Observable.Interval(TimeSpan.FromMilliseconds(100)); using (timer.Do(x => Console.WriteLine("!")).Subscribe(tick => DoSomething())) { Console.ReadLine(); } } private void DoSomething() { Console.Write("<"); Console.Write(DateTime.Now.ToString("HH:mm:ss.fff")); Thread.Sleep(1000); Console.WriteLine(">"); }

运行此命令时,将获得以下输出:

When you run this you'll get this kind of output:

! <16:54:57.111> ! <16:54:58.112> ! <16:54:59.113> ! <16:55:00.113> ! <16:55:01.114> ! <16:55:02.115> ! <16:55:03.116> ! <16:55:04.117> ! <16:55:05.118> ! <16:55:06.119

已经在确保没有重叠.

更多推荐

在单个并发执行限制下,使用Rx运行定期任务的好方法是什么?

本文发布于:2023-11-06 09:44:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563347.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Rx

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!