简体   繁体   中英

reading a file into stream in windows store App without using async/await

I want to read a file from the assets into a stream, I currently use it as the following:

public async void LoadWidthOfUnicodesData()
{

    string dataFile = @"Assets\QuranData\Data_Font1.xml";
    StorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    StorageFile file = await InstallationFolder.GetFileAsync(dataFile);
    Stream readStream = await file.OpenStreamForReadAsync();            
    DataContractSerializer ser = new DataContractSerializer(typeof(List<UniCodeWidth>));
    WidthOfUnicodes = (List<UniCodeWidth>)ser.ReadObject(readStream);
    for (int i = 0; i < WidthOfUnicodes.Count; i++)
    {
        WidthOfUnicodesDict.Add(WidthOfUnicodes[i].UniCode, WidthOfUnicodes[i].Width);
    }
}

The only problem with that, is that part is in my viewmodel, and as it's a non-blocking operation, when the VM initializes with the View as its DataContext, the constructor does what it's supposed to do to fill the view but I always get an exception at using the WidthOfUnicodesDict because it's not yet filled with the data.

What I want to do, is either make the reading to stream a synchronous method (without using async/await) which so far I don't know how to do it on windows store. or somehow make the VM constructor waits till this operation finishes and notifies it's done.

You can fetch a file without async/await semantics like this:

var file = Package.Current.InstalledLocation.GetFileAsync(Folder)
               .GetAwaiter()
               .GetResult();

I don't know how to get a stream, but you can get an IBuffer or read it as text, using FileIO :

string content = FileIO.ReadTextAsync(file).GetAwaiter().GetResult();
IList lines = FileIO.ReadLinesAsync(file).GetAwaiter().GetResult();
IBuffer buffer = FileIO.ReadBufferAsync(file).GetAwaiter().GetResult();

I've done this before and it doesn't cause any deadlocks.

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