我的任务是将每秒30次来自传感器的数据写入一个.csv
文件。如果sersor发送了错误的数据,我不会写它,而只是等待。如果数据还可以,我需要创建一个新文件并开始将数据写入那里。这是我的代码:
class FileWriter
{
string filename;
public FileWriter()
{
}
public void SetFilename(string filename)
{
this.filename = filename;
}
public async void WriteData(string data)
{
StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (var outputStream = stream.GetOutputStreamAt(stream.Size))
{
using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
{
dataWriter.WriteString(data);
await dataWriter.StoreAsync();
}
await outputStream.FlushAsync();
}
stream.Dispose();
}
}
但是我总是得到:
Exception thrown: 'System.IO.FileLoadException' in
System.Private.CoreLib.ni.dll
WinRT information: The file is in use. Please close the file before continuing.
FileLoadException: The process cannot access the file because it is being used by another process.
我认为是因为文件异步打开,并且没有时间每秒打开30次。但是我不知道如何解决它。
编辑:更多详细信息。
我拿了this example。有一个类SpatialMappingObserver
,它有一个方法Update()
,每秒被调用30次。在那里,我打电话给WriteData()
,将Hololens Camera的状态写入文件中。由于Update()
不是异步的,因此无法调用await WriteData()
。
答案 0 :(得分:0)
您应该使用锁来确保在给定的时间只有一个线程正在写入文件:
class FileWriter
{
static readonly object _filelock = new object();
string filename;
public FileWriter()
{
}
public void SetFilename(string filename)
{
this.filename = filename;
}
public async void WriteData(string data)
{
lock (_filelock)
{
StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
using(var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outputStream = stream.GetOutputStreamAt(stream.Size))
{
using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
{
dataWriter.WriteString(data);
await dataWriter.StoreAsync();
}
await outputStream.FlushAsync();
}
}
}
}
}
我还认为您的CreationCollisionOption必须设置为OpenIfExists。