我要运行定期任务,但要限制在任何给定时间最多只能运行一种方法的执行.
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运行定期任务的好方法是什么?
发布评论