使用rx以随机时间间隔生成数字

时间:2015-06-09 13:47:01

标签: system.reactive

如何使用Rx.Net生成一个数字列表,如0-100,其中每个数字是随机生成的?

编辑:

似乎有效

    public void NonBlocking_event_driven()
    {
        var random = new Random();
        var ob = Observable.Create<int>(
        observer =>
        {
            timer.Interval = 1000;
            timer.Elapsed += (s, e) => observer.OnNext(random.Next(0, 3));
            timer.Elapsed += OnTimerElapsed;
            timer.Start();
            return Disposable.Empty;
        });
        var subscription = ob.Subscribe(UserAction);
        Console.ReadLine();
        subscription.Dispose();
    }
    private void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        var random = new Random();
        timer.Interval = random.Next(1, 10)*1000;
        Console.WriteLine(e.SignalTime);
    }

1 个答案:

答案 0 :(得分:5)

有一个操作员,你可以使用Generate:

var source = Observable.Generate(
  0,
  x => x < 100,
  x => x + 1,
  _ => random.Next(0, 3),
  _ => TimeSpan.FromMilliseconds(random.Next(1, 10)* 1000));

source.Subscribe(x => Console.WriteLine(x));