I have a class that is designed to provide quick access to some metadata for some specific files that are used multiple times throughout my application. Unfortunately some of the metadata can only be extracted with a very long running method call.
I have another class that provides an async wrapper for the long running method (can be 5 or more minutes depending on the size of the file), but I'm trying to figure out how to call this async method and if it would be appropriate to put it into the constructor, or if there is a better design pattern for this scenario.
Here's some pseudo code to try and illustrate my question:
public class MetaData
{
public string Data1 { get; private set; }
public string Data2 { get; private set; }
public MetaData(String filepath)
{
var extractor = new ExtractMetaData(filepath); //create instance of class that fetches the metadata
this.Data1 = extractor.GetData1(); // short running method
extractor.Data2Received += Data2Received;
extractor.GetData2Async(); // long running method, called with via async method
}
private void Data2Received(object sender, MetaDataEventArgs args)
{
this.Data2 = args.Data; // finally set Data2 property
}
}
class ExtractMetaData
{
public event Data2ReceivedEventHandler Data2Received;
public ExtractMetaData (string filePath) { }
public String GetData1(); // very fast method to get Data1
public void GetData2Async(); // very slow method to get Data2
}
What I'm trying to figure out is if there is better way to accomplish this?
With my code now, there is virtually no wait for MetaData to be constructed, but if someone were to try to access the MetaData.Data2 property before the GetData2Async() method returns and fires the Data2Received event, they are going to get a null response. But if they call if after it is returned, it will contain the correct information. Since there is really no way to notify the user that this method has completed, I'm worried this will turn into a bad user experience as they don't havr to wait for the constructor, but have to wait for all of the properties to be set.