簡體   English   中英

如何防止應用在WinRT中使用文件

[英]How to prevent app from using file in WinRT

我有幾個線程的應用程序。 第一個線程寫入StorageFile ,第二個線程從相同的StorageFile讀取。 問題是,當第一個線程寫入文件時,我無法阻止第二個線程讀取該文件。 這里是否有類似“ Using關鍵字”之類的東西,可以用來對文件進行單次訪問?

在StackOverflow上也有類似的問題,但它不適合我的解決方案。

我的代碼:

    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;
        }
    }

我最終通過在內存中而不是文件上的數據上添加鎖來解決了這個問題,盡管這很費時,但很費時。 但是,在根據Srirama Sakthivel的提示找到解決方案的過程中,我發現了這個非常有用的主題。 希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM