call_once for C#

No comments

Tuesday, February 25, 2014

One of the useful gems that made it into C++11 Standard Template Libraries (STD) is call_once, this nifty little method makes sure that specific code is called only once (duh) and it follows these 3 rules:
  • Exactly one execution of exactly one of the functions (passed as f to the invocations in the group) is performed. It is undefined which function will be selected for execution. The selected function runs in the same thread as
    thecall_once invocation it was passed to.
  • No invocation in the group returns before the abovementioned execution of the selected function is completed successfully, that is, doesn't exit via an exception.
  • If the selected function exits via exception, it is propagated to the caller. Another function is then selected and executed.
I needed something similar – I had a method that should only be called once (initialize) and I wanted to implement something similar to the call_once I’ve been using for my C++ development.
My first object was to try and make it as preferment as possible and so I’ve looked for a solution that does not involve locks:
public static class Call
    public static void Once(OnceFlag flag,  Action action)
        if (flag.CheckIfNotCalledAndSet)

since I was  trying to mimic the C++ code I wrote two objects Call (above) and OnceFlag which has all of the magic inside using Interlocked:

public class OnceFlag
    private const int NotCalled = 0;
    private const int Called = 1;
    private int _state = NotCalled;
    internal bool CheckIfCalledAndSet
            var prev = Interlocked.Exchange(ref _state, Called);
            return prev == NotCalled;

    internal void Reset()
        Interlocked.Exchange(ref _state, NotCalled);

I’m using Interlocked as a thread-safe way to check & set the value making sure that only once it would return true – try it:

class Program
    static OnceFlag _flag = new OnceFlag();
    static void Main(string[] args)
        var t1 = new Thread(() => DoOnce(1));
        var t2 = new Thread(() => DoOnce(2));
        var t3 = new Thread(() => DoOnce(3));
        var t4 = new Thread(() => DoOnce(4));



    private static void DoOnce(int index)
        Call.Once(_flag, () => Console.WriteLine("Callled (" + index + ")"));

It’s very simple solution unfortunately not entirely correct –  the method used will only be called once, but requirements 2 & 3 were not implemented. Luckily for me I didn’t need to make sure that exception enable another call to pass through nor did I need to block other calls until the first call finishes.

But I wanted to try and write a proper implementation, unfortunately not as preferment due to the use of locks:

public static void Once(OnceFlagSimple flag, Action action)
    lock (flag)
        if (flag.CheckIfNotCalled)

It works, and since I’m already using lock I can split the check and Set methods and use a bool value inside the flag instead of Interlocked.
  • All other threads are blocked due to lock until first finish running – check!
  • In case of exception other method can execute the once block – check!
  • If exited properly the block would only execute once – check!
But not very good performance due to locking on ever time the method gets called.

I’m still looking for a better way to implement call_once – it’s a good exercise in threading and I might find a cool new ways to use the classes under Threading or Task namespaces.

please let me know if you have a better implementation – that’s what the comments are for…

Navigating your design

No comments

Wednesday, February 12, 2014

Let’s pretend you’re visiting a foreign country and you want to get somewhere interesting, in order to do so you need to drive to this new place, one where you’ve never been before. And so you get into your (rented) car and all you’ve got left to do is to ask yourself - how to find the quickest/simplest/shortest way from where you are to your desired destination?

In my case Well that question depends on when you were asking me..

Navigation 101

My preferred tool of navigation used to be a simple map. I would find my destination on the map and my point of origin and try to decide the optimal route (or at least the one which is easier to remember) and write it down and be on my way.

But I don’t do that anymore…


Meet my little friend


Nowadays all I need to do is tell my trusty GPS (A.K.A phone) where I want to go and it would guide me step by step until I arrive at my destination.

Unlike the map of days of old – he knows when the road is blocked and can update my route if I made a wrong turn left (as I do from time to time). It even can suggest a route based on current traffic conditions – a trick which my map is yet to learn.

When using a GPS I find that I no longer care about the entire road but only how long do I have until the next turn.

All in all a good driving experience.

What does it have to do with Software development?

If you know me you know where I heading with this, if not – keep on reading.


It occurred to me last week while teaching Test Driven Development how similar is this practice to using a GPS – when using TDD I know where I want to get but instead of trying to plan the entire trip in advance, I take small incremental steps (turn right here, exit on the 2nd lane, drive through tunnel etc.) until I reach my destination.

When looking at my code design in that perspective I also understood something else –The practice of designing the implementation before writing code is very similar to planning the trip using a map – it would work for small (short) problems but as soon as the trip/problem becomes too big, too complicated or you run into any obstacles (feature change, design bugs, annoying manager) – the map needs to be consulted again, and hopefully while having a good idea where you are.

Another point where using my GPS and writing my code are similar is the fact that although I write my code iteratively I always keep my eyes on big picture – architecture, use case and so on. In a similar matter usually when using a GPS I’ll have a look at the proposed route from start to end – just to make sure that the GPS does not try to take me through “interesting” terrain (dirt roads - happened before) or somewhere I don’t (or can’t) go to - a particularly faulty GPS has tried to get rid of me by suggesting I pass the border – obviously I’ve stopped using that one.


When driving – which to you prefer? the old fashioned, fixed route of the map or the updating, simple directions the GPS provide?


I believe the same rule should apply to your code as well.

Related Posts Plugin for WordPress, Blogger...