What's a good way to run periodic tasks using Rx, with a single concurrent execution restriction?

后端 未结 4 1501

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.

I was experimenting with Rx, but I am no

4条回答
  •  甜味超标
    2020-12-11 04:52

    You are on the right track, you can use Select + Concat to flatten out the observable and limit the number of inflight requests (Note: if your task takes longer than the interval time, then they will start to stack up since they can't execute fast enough):

    var source = Observable.Interval(TimeSpan.FromMilliseconds(100))
              //I assume you are doing async work since you want to limit concurrency
              .Select(_ => Observable.FromAsync(() => DoSomethingAsync()))
              //This is equivalent to calling Merge(1)
              .Concat();
    
    source.Subscribe(/*Handle the result of each operation*/);
    

提交回复
热议问题