Dienstag, 4. Dezember 2012

Windows Phone 8–Parallel async access fixed

Yesterday I have changed my file IO operations from IsolatedStorage (Windows Phone 7) to Windows.Storage classes (WinRT API for Windows Phone 8). One problem with the asynchronous call is that there could now be parallel calls to the same resource (in this case a file). With async methods you cannot use the common lock mechanism :-(

But my colleague Matthias (@JauMatt) has already found in the web a very nice solution for that: http://qedcode.com/content/awaitable-critical-section

My new code which using the class AwaitableCriticalSection looks than like this and works properly for Windows Phone 8, too:

        public static async Task SaveList<T>(string folderName, string dataName, List<T> dataList) where T : class
        {
            StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
 
            if (!await applicationFolder.FolderExistsAsync(folderName))
            {
                applicationFolder.CreateFolderAsync(dataName);
            }
 
            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
 
            using (var section = await CriticalSection.EnterAsync())
            {
 
                StorageFile file =
                    await
                    applicationFolder.CreateFileAsync(fileStreamName, CreationCollisionOption.ReplaceExisting);
                using (IRandomAccessStream randomAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IOutputStream outStream = randomAccessStream.GetOutputStreamAt(0))
                    {
                        var serializer = new DataContractSerializer(typeof (List<T>));
                        serializer.WriteObject(outStream.AsStreamForWrite(), dataList);
                        await outStream.FlushAsync();
                    }
                }
            }
        }

Kommentare:

  1. Yeah, this code works pretty well in my Windows 8 app. Hence I gave Patric the hint to try it on Windows Phone 8 and as you can see... it seems to work well. Win8/WP8 code exchange FTW! :-)

    Cheers, Matthias (@JauMatt)

    AntwortenLöschen
  2. Hey Patric, did you know that you can now use SQLite on WP8? Biggest advantage: possibility of 1 codebase with Win8 (if you should use it there as well...).

    ~ Matthias

    AntwortenLöschen
  3. Thanks Matthias for your tip with the SQLite solution on Windows Phone 8. I will try this, as soon as possible.

    AntwortenLöschen
  4. Hi, i was just wondering if it is possible to make not a general_reader_lock, but a per-file lock? Like mutexes with names.

    AntwortenLöschen