C# 处理WP中的文件--oplock已损坏

C# 处理WP中的文件--oplock已损坏,c#,windows-phone-8.1,C#,Windows Phone 8.1,在某些情况下,我尝试读取Windows Phone 8.1中的文件,在其他情况下尝试写入该文件。我使用以下代码来阅读它: var folder = ApplicationData.Current.LocalFolder; try { var connectionsFile = await folder.OpenStreamForReadAsync("connections"); using (var streamReader = new StreamReader(connecti

在某些情况下,我尝试读取Windows Phone 8.1中的文件,在其他情况下尝试写入该文件。我使用以下代码来阅读它:

var folder = ApplicationData.Current.LocalFolder;
try
{
    var connectionsFile = await folder.OpenStreamForReadAsync("connections");
    using (var streamReader = new StreamReader(connectionsFile, Encoding.Unicode))
    {
        while (!streamReader.EndOfStream)
        {
            String con = await streamReader.ReadLineAsync();
            String[] props = con.Split('\t');
            Connection newConnection = new Connection() { Name = props[0], Url = props[1] };
            ConnectionsCollection.Add(newCollection);
        }
        await connectionsFile.FlushAsync();
        connectionsFile.Dispose();
     }
}
catch(Exception e)
{
    //handle exception
}

我的问题是,它不断地命中catch,内部异常是“与此oplock关联的句柄已关闭。oplock现在已损坏。”(我在尝试写入时遇到相同的错误。)我无法找出问题所在,特别是因为我成功地使用相同的代码在另外两个地方读取相同的文件

我认为您需要删除
等待连接文件.FlushAsync()行,因为您正在使用该文件进行读取。同时删除
connectionsFile.Dispose()
并在ConnectionFile分配中使用
using(…)

var folder = ApplicationData.Current.LocalFolder;
try
{
    using (var connectionsFile = await folder.OpenStreamForReadAsync("connections"))
    using (var streamReader = new StreamReader(connectionsFile, Encoding.Unicode))
    {
        while (!streamReader.EndOfStream)
        {
            String con = await streamReader.ReadLineAsync();
            String[] props = con.Split('\t');
            Connection newConnection = new Connection() {Name = props[0], Url = props[1]};
            ConnectionsCollection.Add(newCollection);
        }
    }
}
catch (Exception e)
{
    //handle exception
}

我希望它能有所帮助。

我认为您需要删除
等待连接文件.FlushAsync()行,因为您正在使用该文件进行读取。同时删除
connectionsFile.Dispose()
并在ConnectionFile分配中使用
using(…)
。@Shawn该错误可能是由于并发线程造成的。可能您正在尝试同时访问同一个文件。我让它只从文件中读取一次,但它仍然会给出错误。