Tag Archives: csharp

A Background Ticker, now in C++ with PPL

Unfortunately, the Reactive Extensions for C++ (Rx++) did not work for me as smoothly as their C# counterpart. My goal is to recreate the background ticker from the Rx version. The first, and perhaps not the last example implementation will be using the Parallel Patterns Library by Microsoft, which uses the Concurrency Runtime. The goal is to write a code that abstracts the threads away, and uses some background scheduler to schedule calls to functions in an asynchronous manner.

Here, asynchronous calls will be done by tickers, one of which will poll a value from a bogus frequency meter and write it to the console, whereas the other one will just write “tick”.

First, the frequency meter that gives random values around 62 (a magic number):

#include <mutex>
#include <random>
class FrequencyMeter
{
	mutable std::mt19937 gen;
	std::uniform_int_distribution<int> dis;
	mutable std::mutex m;
public:
	FrequencyMeter() :
		dis(0,3),
		gen(std::random_device()())
	{}

	int Hz() const
	{
		std::lock_guard<std::mutex> lock(m);
		return 60+dis(gen);
	}
};

This class is not the primary concern here, but if the Hz value is accessed from multiple threads, the access should perhaps be serialized (by a mutex here).

Now, one of the side wishes for the ticker is the ability to start and stop it any time. The ticker should also not care what it executes, hence we can take an std::function for now, or perhaps anything callable. Howerver, having c++11 lambdas, it’s easy to convert to standard function (thread-safety and ownership issues notwithstanding yet). Following the examples for cancellation tokens, one can write a small wrapper that will tick at predefined intervals (see full code), wrapping a simple loop:

while (running)
{
	// Check for cancellation. 
	if (concurrency::is_task_cancellation_requested())
	{
		running = false;
		concurrency::cancel_current_task();
	}
	else
	{
		this->tick_once();
		concurrency::wait(interval);						
	}
}

In the small test program, the frequency meter is instantiated and the first ticker is started, ticking once a quarter of a second:

FrequencyMeter FM;
active_ticker measure([&FM]{std::cout<<FM.Hz()<<std::endl;});
measure.start(250);

Then another ticker is started:

active_ticker ticker([]{std::cout<<"tick"<<std::endl;});
ticker.start(500);

And some wait, start and stop logic:

wait(2000); //see the output for a couple of seconds
measure.stop(); //stop the frequency meter
wait(2000); //wait some more
ticker.stop(); //stop ticking
measure.start(250); //start measuring again
wait(2000); //and wait a bit more
measure.stop();

The output looks like this:

60
tick
61
62
tick
61
62
tick
60
60
Canceling measurement ...
tick
60
tick
tick
tick
Restarting measurement ...
tick
60
63
62
61
62
62
62
Done

Any other technology to try elegant ticking (tinkering) with? TBB, zeromq in process?

The WPF + ReactiveUI Refactored Version of the Responsive UI Hello World

Overview

To recapitulate, the first article in the series used Reactive Extensions (Rx) directly in Windows Forms UI logic to implement a UI with a simulated background calculation, which delivered a timestamp each second. The rest of the application was an input text box, for which, when the user inputs the text, the word count is calculated asynchronously and posted into another read-only text box.

The second article introduced a WPF version of the same UI with a viewmodel that implements the INotifyPropertyChanged interface and supplies the ticker text and the word count as bindable properties. The text being input was delivered to the viewmodel via an event converted to an observable sequence, which was used to update the TextInput property of the viewmodel. The WordCount was updated from the setter of TextInput.

The third article recreated the WPF implementation in WinForms using the same viewmodel, which is shared between the two projects. The third UI implementation introduced throttling of the TextInput changes to 0.3 seconds so that the word count is updated only when the user pauses for at least a third of a second to take a look at the result.

The Refactored WPF Version

In this article, the WPF UI is further refactored, so that the concerns are separated further. These are organized as follows:

Create a sequence of some calculation results

These are timestamps in this case, implemented as an object, providing an IObservable<string> property Ticker:

public class BackgroundTicker
{
    public IObservable<string> Ticker
    {
        get
        {
            return Observable
                .Interval(TimeSpan.FromSeconds(1))
                .Select(_ => DateTime.Now.ToLongTimeString());
        }
    }
}

The observable sequence is active, delivering a value every second.

Count words in text asynchronously and provide another property calculated in the background

This viewmodel is finally implemented using ReactiveUI:

public class WordCounterModel : ReactiveObject

The word count and the input text are ReactiveUI boilerplate:

string _TextInput;
public string TextInput
{
    get { return _TextInput; }
    set { this.RaiseAndSetIfChanged(ref _TextInput, value); }
}

ObservableAsPropertyHelper<int> _WordCount;
public int WordCount
{
    get { return _WordCount.Value; }
}

The value sequence of the background ticker is injected at construction time using its observable member. The word count and the background ticker properties are implemented using an ObservableAsPropertyHelper.
The results of the background ticker are exposed via a property:

ObservableAsPropertyHelper<string> _BackgroundTicker;
public string BackgroundTicker
{
    get { return _BackgroundTicker.Value; }
}

the helper is initialized from the constructor-supplied observable:

someBackgroundTicker
    .ToProperty(this, ticker => ticker.BackgroundTicker, out _BackgroundTicker);

And finally, the word count logic is implemented as an output property, transforming the sequence of strings into a sequence of integers:

this.WhenAnyValue(x => x.TextInput)
    .Where(x => !string.IsNullOrWhiteSpace(x))
    .Select(x => x
        .Split()
        .Where(word => !string.IsNullOrWhiteSpace(word))
        .Count())
    .ToProperty(this, vm => vm.WordCount, out _WordCount);

The throttling can be removed from the viewmodel, as the WPF 4.5 has a Delay binding property, which can be used for the same purpose on the view side, freeing the viewmodel from that concern.

Provide a Graphical UI

Now let’s look at the view. The event subscription is gone and data binding is implemented in XAML declaratively. The DataContext of the main window is initialized with an instance of the viewmodel, which is initialized with an observable from an instance of a background ticker:

ViewModels.BackgroundTicker Ticker=new ViewModels.BackgroundTicker();
ViewModels.WordCounterModel VM = new ViewModels.WordCounterModel(Ticker.Ticker);
DataContext = VM;

This instantiation can be definitely made in XAML as well, nullifying the amount of C# code for the view, as for example in the following article.

The background ticker and the word count are now bound one-way and marked asynchronous.

<TextBox ... Text="{Binding BackgroundTicker,IsAsync=True,Mode=OneWay}"></TextBox>
<TextBox ... Text="{Binding WordCount,IsAsync=True,Mode=OneWay}"></TextBox>

And finally, the binding of the input text is configured in XAML to be throttled to 300 milliseconds and bind on PropertyChanged events of the Text property of the text box:

<TextBox ... Text="{Binding TextInput, UpdateSourceTrigger=PropertyChanged, Delay=300}"></TextBox>

Source Code

https://github.com/d-led/reactiveexamples

First refactoring of the WinForms UI example

The hello world UI example started here is at first sight not optimal to demonstrate the positive effects of UI and app logic separation, since the amount of boilerplate code required to write the viewmodel without using a specialized framework is larger than the savings in the UI logic code. However, the testability of the viewmodel is granted having created the separation. The example also does not contain an explicitly defined model, apart from the “current” DateTime.

Windows Forms have bindings that understand the INotifyPropertyChanged interface, which we can recycle in the first refactoring of the WinForms example.

The complete project can be viewed on GitHub. As you will notice, the viewmodel is shared between this version and the first WPF one.

Only in the Form1_Load event handler of the form is tackled here.

The old code:

Observable.Interval(TimeSpan.FromSeconds(1))
    .ObserveOn(this)
    .Subscribe(x => textBox1.Text = DateTime.Now.ToLongTimeString());

var textChanged = Observable.FromEventPattern
    <EventHandler, EventArgs>(
    handler => handler.Invoke,
    h => textBox3.TextChanged+= h,
    h => textBox3.TextChanged-= h);

textChanged
    .ObserveOn(this) // scheduled on the Form's scheduler
    .Subscribe(x => textBox2.Text =
        textBox3.Text
        .Split()
        .DefaultIfEmpty()
        .Where(s=>s.Trim().Length>0)
        .Count()
        .ToString());

and the new one:

ViewModels.MyViewModel VM = new ViewModels.MyViewModel();

textBox1.DataBindings.Add("Text", VM, "CurrentTime");
textBox2.DataBindings.Add("Text", VM, "WordCount");

var textChanged = Observable.FromEventPattern
    <EventHandler, EventArgs>(
    handler => handler.Invoke,
    h => textBox3.TextChanged += h,
    h => textBox3.TextChanged -= h);

textChanged
    .Throttle(TimeSpan.FromSeconds(0.3))
    .ObserveOn(this)
    .Subscribe(_ => VM.TextInput = textBox3.Text);

1

Still the TextChanged event is used for the update of the viewmodel. The relevant changes are highlighted and are similar to the first WPF version. As you can see, the code is extremely similar to the WPF version.

The updated version instantiates the viewmodel, creates the bindings and subscribes the update of the viewmodel’s text. As a slight responsiveness improvement over the first two versions, the observable TextChanged events are throttled to 0.3 seconds with the idea that the word count is of no interest to the user during typing.

When the application becomes more elaborate, it’s expected that the savings become substantial, especially when using a specialized MVVM framework, such as ReactiveUI. At this stage, there is still no lifetime control of the observable’s subscriptions.

The next step is to start using ReactiveUI for the viewmodel.

  1. for a more MVVM approach, see a newer article

The WPF Version of the Responsive UI Hello World

What is lacking in the first version of the hello world example is the separation of UI and application logic. A refactored WinForms version may be the topic of a future post.

The next step in the discovery of Rx is to create a similar software using WPF. The details can be viewed in the source code, so let’s concentrate on the peculiarities. In this version, pure Rx will be used without ReactiveUI.

wpf version of ui hello world

WPF brings a possibility of total separation of UI, UI logic and application logic. A part of the application can be implemented by bindings to a viewmodel. The viewmodel has to implement the INotifyPropertyChanged interface. We’ll choose the implementation from here for the moment.

The viewmodel is defined as follows, omitting the INotifyPropertyChanged details:

public class MyViewModel : INotifyPropertyChanged
{
    //http://msdn.microsoft.com/en-us/library/ms229614.aspx details ...

    string _CurrentTime;
    public string CurrentTime
    {
        get { return _CurrentTime; }
        private set
        {
            if (value != _CurrentTime)
            {
                _CurrentTime = value;
                NotifyPropertyChanged();
            }
        }
    }

    string _TextInput;
    public string TextInput
    {
        get { return _TextInput; }
        set
        {
            if (value != _TextInput)
            {
                _TextInput = value;
                NotifyPropertyChanged();
                UpdateWordCount();
            }
        }
    }

    private void UpdateWordCount()
    {
        WordCount = TextInput.Split()
            .DefaultIfEmpty()
            .Where(s => s.Trim().Length > 0)
            .Count();
    }

    int _WordCount;
    public int WordCount
    {
        get { return _WordCount; }
        private set
        {
            if (value != _WordCount)
            {
                _WordCount = value;
                NotifyPropertyChanged();
            }
        }
    }

    public MyViewModel()
    {
        Observable.Interval(TimeSpan.FromSeconds(1))
            .Subscribe(_ => CurrentTime = DateTime.Now.ToLongTimeString());
    }
}

By using the separation the application logic becomes testable without building a UI, as the viewmodel is not dependent on System.Windows*.

The word count and the current time field can be bound to the controls by using the standard binding mechanism:

<TextBox ... Text="{Binding CurrentTime}"></TextBox>
<TextBox ... Text="{Binding WordCount}"></TextBox>

However, if we want the word count to be updated on every text change and not after focus change, we’ll have to use the TextChanged of the third text box to update the viewmodel. The update of the word count is currently implemented in the setter for the TextInput property on line 29. Using ReactiveUI this will change as well.

The configuration of the UI by code-behind looks as follows:

ViewModels.MyViewModel VM = new ViewModels.MyViewModel();
DataContext = VM;
var textChanged = Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
    handler => handler.Invoke,
    h => textBox3.TextChanged += h,
    h => textBox3.TextChanged -= h);
textChanged.Subscribe(_ => VM.TextInput = textBox3.Text);

Compared to the first WinForms version it has two responsibilities less – the current time update logic and the word count logic, which is now in the viewmodel.

As the next step, the implementation of the viewmodel should be further simplified.

Source code can be found here.

A Responsive Windows Forms UI using Reactive Extensions

For WPF programming there is a Reactive Extensions extension called ReactiveUI. I like the idea very much, but the last time I have looked at the online documentation, it was slightly out of sync with the current version, and the examples are slightly more elaborate than hello world. I’ll have to return to ReactiveUI at a later point in time.

As it seems, many people still use WinForms. A typical Forms application contains quite a number of event handlers. What Rx promises is a declarative design of your program (UI) logic. Without getting too concerned with lifetime management of this hello world example, here it is:

Responsive WinForms using Rx

The first TextBox gets updated asynchronously with the current time, the second TextBox shows the word count of the text entered in the third TextBox. All that is defined in a single Load event handler, private void Form1_Load(…). You can get the code here.

The initialization of the logic (in Form1_Load) is as follows:

Update textBox1 with the current time asynchronously every second

Observable.Interval(TimeSpan.FromSeconds(1))
          .ObserveOn(this) // scheduled on the Form's scheduler
          .Subscribe(_ => textBox1.Text = DateTime.Now.ToLongTimeString());

No threading code needed :).

Convert an event handler into an observable and set its registration

var textChanged = Observable.FromEventPattern<EventHandler, EventArgs>
 (
  handler => handler.Invoke,
  h => textBox3.TextChanged+= h,
  h => textBox3.TextChanged-= h
 );

Subscribe to the textChanged observable in order to update the word count

textChanged
    .ObserveOn(this) // scheduled on the Form's scheduler
    .Subscribe(x => textBox2.Text =
        textBox3.Text
        .Split()
        .DefaultIfEmpty()
        .Where(s=>s.Trim().Length>0)
        .Count()
        .ToString());

That’s it. No other explicit event handlers, just these observables with lambdas.

Continued here….

Update: Since the original post, a lot has changed. ReactiveUI has a shiny new docs site, a lot of API improvements, and improved exposure.

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.

pathetic – A hopefully user-friendly windows tool to edit user environment variables that are semicolon-separated path lists

I’ve always wanted to clean that PATH user environment variable, but never got around doing this, hence this little tool. It has at least one bug, and it isn’t well written, but it helped me already.

Get the current source on github or the alpha version binary here.