读取/写入通用应用程序的异步文件

时间:2016-06-02 13:40:08

标签: c# xml asynchronous win-universal-app uwp

我试图在c#中为通用应用程序读取/编写异步文件。 当我第一次写入和读取文件时,它可以工作......但是当我重新尝试它时,有两个错误:1。未授权访问2.处理OPLOCK已关闭

似乎方法尚未完成,因此数据不是免费的

(在我的框架中是一个向List添加新成员的按钮,然后列表将在XML数据中序列化。当我重新导航到该页面时,该XML表格将被反序列化回该列表,因为内容应显示)

List<Immobilie> immoListe = new List<Immobilie>();
private const string FileName_ImmoObjects = "ImmoObjects.xml";
StorageFolder sFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
IStorageFile latestImmoListFile;

 public Startmenue()
    {
        this.InitializeComponent();
        immoListe.Add(new Immobilie()); // for testing creating an XML first
        immoListe[0].adresse = "Foo1";  
        immoListe.Add(new Immobilie());
        immoListe[1].adresse = "Foo2";
        WriteImmoListAsync();   
        ReadImmoListAsync();   // These two steps working

        WriteImmoListAsync(); // everything more causes error  
        ReadImmoListAsync();   

    }

public async void WriteImmoListAsync()
    {
        try
        {
            IStorageFolder folder = await sFolder.CreateFolderAsync("Saves", CreationCollisionOption.OpenIfExists);
            latestImmoListFile = await folder.CreateFileAsync(FileName_ImmoObjects, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await latestImmoListFile.OpenAsync(FileAccessMode.ReadWrite))
            using (Stream outputStream = stream.AsStreamForWrite())
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(List<Immobilie>));
                serializer.WriteObject(outputStream, immoListe);
            }

        }
        catch (Exception e)
        {
            var d = new MessageDialog(e.ToString());
            await d.ShowAsync();
        }
    }



    public async void ReadImmoListAsync()
    {
        int i = 0;
        try
        {
            IStorageFolder folder = await sFolder.GetFolderAsync("Saves");
            i = 1;
            latestImmoListFile = await folder.GetFileAsync(FileName_ImmoObjects);
            i = 2;
            using (IRandomAccessStream stream = await latestImmoListFile.OpenAsync(FileAccessMode.Read))
            {
                i = 3;
                using (Stream inputStream = stream.AsStreamForRead())
                {
                    i = 4;
                    DataContractSerializer deserializer = new DataContractSerializer(typeof(List<Immobilie>));
                    i = 5;
                    immoListe = (List<Immobilie>)deserializer.ReadObject(inputStream);
                }
            }

        }
        catch (Exception e)
        {
            var d = new MessageDialog("Fehler I = " + i + "\n" + e.ToString());
            await d.ShowAsync();
        }
    }

那么我该怎么办?为什么这么难?(正常的I / O很容易).-。

3 个答案:

答案 0 :(得分:3)

正如我在关于line_space = 16 basicfont = pygame.font.SysFont('MorePerfectDOSVGA', 16) def text_ani(str, tuple): x, y = tuple y = y*line_space ##shift text down by one line char = '' ##new string that will take text one char at a time. Not the best variable name I know. letter = 0 count = 0 for i in range(len(str)): pygame.event.clear() ## this is very important if your event queue is not handled properly elsewhere. Alternativly pygame.event.pump() would work. time.sleep(0.05) ##change this for faster or slower text animation char = char + str[letter] text = basicfont.render(char, False, (2, 241, 16), (0, 0, 0)) #First tuple is text color, second tuple is background color textrect = text.get_rect(topleft=(x, y)) ## x, y's provided in function call. y coordinate amended by line height where needed screen.blit(text, textrect) pygame.display.update(textrect) ## update only the text just added without removing previous lines. count += 1 letter += 1 print char ## for debugging in console, comment out or delete. text_ani('this is line number 1 ', (0, 1)) # text string and x, y coordinate tuple. text_ani('this is line number 2', (0, 2)) text_ani('this is line number 3', (0, 3)) text_ani('', (0, 3)) # this is a blank line 最佳做法的MSDN文章中所描述的,you should avoid async void

async

一旦您的方法正确public async Task WriteImmoListAsync(); public async Task ReadImmoListAsync(); ,您就可以async Task

await

答案 1 :(得分:0)

在等待它们完成之前,您无法再次启动这些方法。上面的代码试图做的是写入一个文件,但在进行处理时,它会尝试打开文件并在第一个方法调用未完成时写入该文件。您需要等待这些方法调用再次运行才能完成 - 使用await关键字在这里会有所帮助

答案 2 :(得分:0)

可能是写入/读取文件的过程仍附加到文件中。您可能希望查看此模式以获取Microsoft的异步文件读/写:

https://msdn.microsoft.com/en-ca/library/mt674879.aspx

另外,请注意,如果读取和写入是从不同进程完成的,那么您将不得不使用互斥锁。以下是对其工作原理的一个很好的解释:

What is a good pattern for using a Global Mutex in C#?