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:
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();
}
}
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.
Tip: avoid
async void; useasync Taskinstead. That enables you to know when the previous operation is complete.