Creating Multiple Timers with Reactive Extensions

后端 未结 3 1482
庸人自扰
庸人自扰 2021-01-16 14:06

I\'ve got a very simple class that I am using to poll a directory for new files. It\'s got the location, a time to start monitoring that location, and an interval (in hours

3条回答
  •  日久生厌
    2021-01-16 14:25

    Hmmm. Does DoWork produce a result that you need to do something with? I'll assume so. You didn't say, but I'll also assume DoWork is synchronous.

    things.ToObservable()
      .SelectMany(thing => Observable
        .Timer(thing.StartTime, TimeSpan.FromHours(thing.Interval))
        .Select(_ => new { thing, result = DoWork(thing.Uri) }))
      .Subscribe(x => Console.WriteLine("thing {0} produced result {1}",
                                        x.thing.Name, x.result));
    

    Here's a version with a hypothetical Task DoWorkAsync(Uri):

    things.ToObservable()
      .SelectMany(thing => Observable
        .Timer(thing.StartTime, TimeSpan.FromHours(thing.Interval))
        .SelectMany(Observable.FromAsync(async () =>
           new { thing, result = await DoWorkAsync(thing.Uri) })))
      .Subscribe(x => Console.WriteLine("thing {0} produced result {1}",
                                        x.thing.Name, x.result));
    

    This version assumes that DoWorkAsync will finish long before the interval expires and starts up a new instance and so does not guard against having concurrent DoWorkAsync running for the same Thing instance.

提交回复
热议问题