Discount for my course: High Performance Coding with .NET Core and C#

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 initialize the class. The problem with this is that it is guaranteed that someone will forget to call the initialization. So one requirement 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 completely.

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

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



    public class ClassWithLongInitialization
    {
        private Task initialization;

        public ClassWithLongInitialization()
        {
            initialization = new Task(() => InitializeClass());
            initialization.Start();
        }

        private void InitializeClass()
        {

            System.Threading.Thread.Sleep(2000);
            Console.WriteLine("class initialized");

        }

        public async Task MethodToUseTheClass()
        {
            await initialization;
            Console.WriteLine("MethodToUseTheClass");
        }

    }

The constructor of the class automatically starts the initialization. The MethodToUseTheClass is the method which uses resources that are initialized in the InitializeClass 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 immediately. 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 than that from the outside the initialization is completely hidden.


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


;