Classes with long initialization process implemented with Tasks in C#
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;
initialization = new Task(() => InitializeClass());
private void InitializeClass()
public async Task MethodToUseTheCla
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();