Monday, November 5, 2012

Adding reactivity to NetMonitor

It was long time ago when I last time wrote about updates in the NetMonitor project. I was just using it from time to time to diagnose my network connection and it worked pretty well. However, I wasn't happy with its internals, especially with PingService implementation as it was rather complex for such simple job - it had to deal with entities from System.Threading namespace (e.g. Timer) to get called from time to time in background thread and this only added complexity without adding any business value.

Some time ago I tried playing with Task Parallel Library, but eventually it appeared that TPL is not applicable in this scenario.

This time I've found Rx Extensions and I really liked the approach. My task with sequential background execution is solved with the help of the extensions quite gracefully (here is simplified version):

var service = new PingService("");

// Every second the ping service will be called from background thread, producing a sequence of metrics
var metrics = Observable.Interval(TimeSpan.FromSeconds(1))
    .Select(i => service.Execute());

// Consuming the sequence of metrics and updating UI
subscription = metrics.Subscribe(
    metric => Console.WriteLine(metric.RoundtripTime),
    exception => Console.WriteLine(exception.Message));

Applying Rx Extensions drastically simplified the service itself and program environment as additionally I got rid of events and handlers, I am satisfied with the changes it brought. In my scenario it looks like a simple messaging bus between services and their consumers.

I'm pretty confident that Reactive Extensions can change your attitude to composing asynchronous and event-based programs (as it once happened with invention of LINQ for data querying). More on Rx can be found on MSDN, 101 Samples, IntroToRx.

No comments:

Post a Comment