Gergely Kalapos

Classes with long initialization process implemented with Tasks in C#

Posted on July 09, 2014

As the first post I would like to introduce a really easy, but very useful pattern in C#.

When I work on Windows 8 Apps I often have the situation where I have a class which has a longer initialization process (e.g. deserialising some state from the file system, loading data over the network, make some complicated calculation, etc…). One solution would be to write a public "initialize" method and call it first to initilize the class. The problem with this is that it is garanteed that someone will forget to call the initialization. So one requieroment here is that the class should behave from the outside like any other class which does not need this initialization. The main reason for this is, that this initialization is most of the time really quick, and it happens only once anyway, so why not hide it complately.

In this post I would like to describe the pattern that I use in such a case.

So the basic idea is that the initialization happens in a Task and this task blocks every method that use reasources which are usable only after the initialization process is done.

    public class ClassWithLongInitialization
        private Task initialization;

        public ClassWithLongInitialization()
            initialization = new Task(() => InitializeClass());

        private void InitializeClass()

            Console.WriteLine("class initialized");


        public async Task MethodToUseTheClass()
            await initialization;


The constructor of the class automatically starts the initialization. The MethodToUseTheClass is the method which uses resources that are initialized in the InitializeCalss method. The first line says that we wait until the initialization is done (if we do not call the method right after the creation of the class but a little bit later then there is a high probability, that we jump to the next line in the method immediatly. If this is not the case, the method waits until the initialization is finished.

From the outside the class behaves like any other class.

Here is an example where we use this class: Yes, there is an await there (and if you forget this you get a warning), so we do not block the main thread (which is I think expected in such a case). But other then that from the outside the initialization is completly hidden.

   var myInstance = new ClassWithLongInitialization();
   await myInstance.MethodToUseTheClass();