Jason Rowe

Be curious! Choose your own adventure.

System.Reactive IScheduler Hello World

I’ve been following the Reactive Extensions work on blogs, podcasts and forums. It sounds and looks amazing. The icing on the cake is Bart De Smet is going to be involved and it uses the new Parallel framework (TPL).

Photo of cake icing to make some odd point.

After watching this great video Controlling concurrency in Rx on the RX team blog. I was inspired to start trying out the scheduler. Below are my basic code snippets that would be the equivalent of a hello world.

The first code snippet below uses the “Now” and “Later” schedulers that are provided. They follow this pattern respectively. Schedule(Action); Schedule(Action, TimeSpan);.

 static void Main(string[] args)
        {
            var timespan = new TimeSpan(0, 0, 5);

            using (Scheduler.Later.Schedule(DoSomeActionLater, timespan))
            {
                using (Scheduler.Now.Schedule(DoSomeAction))
                {
                    Console.WriteLine("type q to quit");

                    while (Console.ReadLine() != "q")
                    {
                        Thread.Sleep(1000);
                        Console.WriteLine("...");
                    }

                }
            }
        }

        public static void DoSomeActionLater()
        {
            Console.WriteLine("Later");
        }

        public static void DoSomeAction()
        {
            Console.WriteLine("Now");
        }

This will give you some output similar to this.

The next snippet uses fixed point recursive scheduling. It follows this format Schedule(Action,TimeSpan)

        static void Main(string[] args)
        {
            var timespan = new TimeSpan(0, 0, 5);
            var scheduler = Scheduler.Default;

            using (scheduler.Schedule(Self =>
               {
                   Console.WriteLine("recursive");
                   Self(timespan);

               }, timespan))
            {

                Console.WriteLine("type q to quit");
                while (Console.ReadLine() != "q")
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("...");
                }
            }
        }

Here is the result from the recursive scheduler.

In the video on IScheduler, it’s mentioned that a scheduler could be written to abstract away time. On CodePlex you can find a simple implementation of a virtual time scheduler TimeMachineScheduler.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *