Tag Archives: asynchronous

Asynchronously access an object’s property repeatedly in C#

A question on Stackoverflow got me thinking of a beautiful way of reporting a value of an object in C# repeatedly, something like polling a sensor. Typically, polling is pull-based, but having been reading Intro to Rx for the second time lately, and being convinced of its push-base structural and syntactic eunoia, I’ve created a solution based on Rx listed below.

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;

namespace rxtest
{
    class FrequencyMeter
    {
        Random rand = new Random();
        public int Hz
        {
            get { return 60+rand.Next(3); }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var obs = Observable.Generate<FrequencyMeter, int>(
                new FrequencyMeter(), //state
                x => !Console.KeyAvailable, // while no key is pressed
                x => x, // no change in the state
                x => x.Hz, // how to get the value
                x => TimeSpan.FromMilliseconds(250), //how often
                Scheduler.Default)
                .DistinctUntilChanged() //show only when changed
                ;

            using (var _ = obs.Subscribe(x => Console.WriteLine(x)))
            {
                var ticks = Observable.Interval(TimeSpan.FromSeconds(0.5))
                           .Subscribe(x=>Console.WriteLine("tick")); //an example only
                Console.WriteLine("Interrupt with a keypress");
                Console.ReadKey();
            }
        }
    }
}

producing an output similar to that:

Interrupt with a keypress
62
60
62
tick
61
60
tick
62
61
tick
60
62
61
tick
62

Now, with Rx available in C++ that would be interesting what will be left of the eunoia.