0

I'm writing Windows Phone 8.1 application and one of its part is LocalStorage access. I wrote code as presented below, but it has some serious issue. I need to initialize service using asynchronous methods and a while after, I'm using one of it's method (which is also asynchronous).

Service : IService
{
    private XmlFormatter xmlFormatter;

    public Service()
    {
        Initialize();
    }

    public async IList<Model> GetModelsAsync()
    {
        return xmlFormatter.GetModels();
    }

    private async void Initialize()
    {
        try
        {                
            StorageFile item = (StorageFile)await ApplicationData.Current.LocalFolder.GetItemAsync(this.settings.Get<string>(SettingNames.DataFilename));

            using (Stream readStream = await item.OpenStreamForReadAsync())
            {
                xmlFormatter = new XmlFormatter(XDocument.Load(readStream));
            }
        }
        catch (FileNotFoundException)
        {
            CreateFile();
            xmlFormatter = new XmlFormatter(null);
        }
        catch (Exception)
        {
            throw;
        }
    }
}

The problem is that GetModelsAsync methods runs before end of Initialize method, so xmlFormatter is null and I recieve NullReferenceException. How can I synchronize these methods?

2 Answers 2

2

There are multiple solutions to this. I would suggest saving the Task that is returned from the Initialize method. I would then in GetModelsAsync call: await _initializeTask; before trying to use the xml formatter.

Another solution is to throw an exception saying that your service is not yet initialized, but since the user is not the one calling Initialize, that would just be bad design.

The third is to make the Initialize method public and place the responsibility on the user to invoke it and make sure that it has finished before invoking the other methods in your class.

Sign up to request clarification or add additional context in comments.

2 Comments

So, you are suggesting me (option 1) to write await _initializeTask; just after opening bracket?
I'm giving you three different solutions, it is up to you to pick one. If you want to use the first solution then I would place the await call right before trying to access the xml formatter.
2

Never do long running processes in ctor, call initialize separately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.