简体   繁体   中英

C# async object initialization

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?

切勿在ctor中执行长时间运行的进程,请单独调用initialize。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM