最近在文件保存、将一文件内容写入另一文件中经常会遇到线程冲突的问题,如,将文件A的内容写入文件B,再将A删除,这样的操作将会涉及以下几个步骤:
(1) 打开B文件,通过文件流初始化DataWriter对象
(2) 打开A文件,通过文件流初始化DataReader对象
(3) 通过DataReader对象加载文件A的内容
(4) 通过DataWriter将内容写入
(5) DataWriter保存
(6) DataWriter刷新
以上每一步都必须一环套一环,若没有确保当前对A、B文件的操作完全结束,而在其它线程又开始操作这些文件,就会经常出现线程冲突。
下面提供对以上步骤一个简单示例:
task<IRandomAccessStream^>(StorageFileB->OpenAsync(FileAccessMode::ReadWrite))
.then([ this](IRandomAccessStream^ raStream)
{
IOutputStream^ outStream = raStream->GetOutputStreamAt( 0);
DataWriter^ bbrw = ref new DataWriter(outStream);
task<IRandomAccessStream^>(StorageFileA->OpenAsync(FileAccessMode::Read))
.then([bbrw, this](IRandomAccessStream^ readStream)
{
DataReader^ dataReader = ref new DataReader(readStream);
task<unsigned int>(dataReader->LoadAsync((unsigned int)readStream->Size)).then([ this,bbrw,dataReader](unsigned int numBytesLoaded)
{
Array<unsigned char, 1>^ fileContent = ref new Array<unsigned char, 1>(numBytesLoaded);
dataReader->ReadBytes(fileContent);
bbrw->WriteBytes(fileContent);
task<unsigned int> store(bbrw->StoreAsync());
store.then([bbrw] (unsigned int)
{
return bbrw->FlushAsync();
}).then([=]( bool flushSucceeded)
{
bbrw->DetachStream();
.then([ this](IRandomAccessStream^ raStream)
{
IOutputStream^ outStream = raStream->GetOutputStreamAt( 0);
DataWriter^ bbrw = ref new DataWriter(outStream);
task<IRandomAccessStream^>(StorageFileA->OpenAsync(FileAccessMode::Read))
.then([bbrw, this](IRandomAccessStream^ readStream)
{
DataReader^ dataReader = ref new DataReader(readStream);
task<unsigned int>(dataReader->LoadAsync((unsigned int)readStream->Size)).then([ this,bbrw,dataReader](unsigned int numBytesLoaded)
{
Array<unsigned char, 1>^ fileContent = ref new Array<unsigned char, 1>(numBytesLoaded);
dataReader->ReadBytes(fileContent);
bbrw->WriteBytes(fileContent);
task<unsigned int> store(bbrw->StoreAsync());
store.then([bbrw] (unsigned int)
{
return bbrw->FlushAsync();
}).then([=]( bool flushSucceeded)
{
bbrw->DetachStream();
Do anything….
});
});
});
});
});
});
});
});
最后一个bbrw->DetachStream()非常重要哦,它是用来分离DataWriter关联流的,如果我们不将之分离,再一次操作文件流时也会容易发生冲突。
如果在项目中会多次同一个文件,一定要确保不要同时操作同一个文件,否则很容易发生线程冲突。若是在不同的模块要操作同一个文件,可以通过信号量来处理。