What can cause GetFileAsync to hang?

2019-09-02 11:37发布

问题:

I've got a simple utility collection for a Windows Store application (a.k.a Metro), but I'm finding that it seems to hang when calling ApplicationData.Current.LocalFolder.GetFileAsync in succession (i.e. as soon as I try to debug it and step through, the problem disappears).

    public static async Task<LocalCache<T>> LoadCache()
    {
        try
        {
            // Get the input stream for the cache
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(GetFileNameForType());
            using (IInputStream inStream = await file.OpenSequentialReadAsync())
            {
                // Deserialize the cache
                DataContractSerializer serializer = new DataContractSerializer(typeof(LocalCache<T>));
                return (LocalCache<T>)serializer.ReadObject(inStream.AsStreamForRead());
            }
        }
        catch (FileNotFoundException)
        {
            return new LocalCache<T>();
        }
    }

There doesn't appear to be any overload to specify a mode to open the file in, and it doesn't appear to return, which has left me kinda stumped. What can I do prevent this deadlock?

回答1:

The most likely cause of this is further up your call stack; I'm guessing there is probably a call to Wait or Result. This will result in deadlock (as described on my blog).

If you're blocking because this is part of initialization or a constructor, then you may be interested in asynchronous lazy initialization (also described on my blog).