简体   繁体   中英

How to prevent app from using file in WinRT

I have application which has several threads. First thread writes into the StorageFile , second thread reads from the same StorageFile . Problem is, I can't prevent second thread from reading that file, while first thread is writing into it. Is here something like Using keyword I can use for getting single access to the file?

There is similar question on StackOverflow, but it doesn't suite to my solution.

My code:

    public async static Task<bool> Save(string filename, object o)
    {
        try
        {
            Stream stream;

            var folder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            stream = await file.OpenStreamForWriteAsync();
            if (o == null || stream == null)
            { }
            else
            {
                DataContractSerializer ser = new DataContractSerializer(o.GetType());
                ser.WriteObject(stream, o);
            }


            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

I finally solved the problem by adding lock on the data in the memory, not on the file, which would be time-consuming, though elegant. However, during finding solutions in reaction to Srirama Sakthivel's hint I found this very useful topic. I hope that will help someone.

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