如何处理StorageFile操作的并发性? [英] How to handle concurrency with StorageFile operations?

查看:70
本文介绍了如何处理StorageFile操作的并发性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写入文件,但是偶尔"我遇到了一些问题,我认为这取决于并发性,因为有时 some ,我得到的是System.UnauthorizedAccessException讯息:

I'm attempting to write to a file but "occasionally" I run into issues that I think are down to concurrency, as some of the time, I'm getting a System.UnauthorizedAccessException with message:

访问被拒绝. (来自HRESULT的异常:0x80070005(E_ACCESSDENIED))

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

...来自以下内容:

...from the following:

public async void SubmitChanges()
{
    DataContractSerializer serializer = 
        new DataContractSerializer(typeof(LocalCache<T>));

    StorageFile file = await ApplicationData.Current.LocalFolder
            .CreateFileAsync(GetFileNameForType(), 
                CreationCollisionOption.ReplaceExisting);

    //Occasionally throws here
    using (var fi = await file.OpenTransactedWriteAsync())
    {
        serializer.WriteObject(fi.Stream.AsStreamForWrite(), this);
        await fi.CommitAsync();
    }
}

我只能假设这是某种程度的并发性,或者它仍然可以在其他地方读取,但是我似乎无法找到一种方法来等待它变为可用-我通常会lock围绕它,但是await不允许这样做,那么其他选项是什么?

I can only assume that this is down to some concurrency, or it being still open for read somewhere else, but I can't seem to find a way to wait for it to become available - I'd normally lock around it, but this is not allowed with await so what are the other options?

推荐答案

通常,直到上一个操作完成后,您才开始下一个操作.

Usually, you just don't start the next operation until the previous operation is complete.

提示:避免使用async void;使用async Task代替.这样一来,您就可以知道上一操作何时完成.

Tip: avoid async void; use async Task instead. That enables you to know when the previous operation is complete.

这篇关于如何处理StorageFile操作的并发性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆