ReadLinesAsync()产生访问冲突 [英] ReadLinesAsync( ) produces access violation
问题描述
我编写了一个函数,该函数可以异步打开并读取文本文件,并将行写入向量中.我收到访问冲突.为什么?
I have written a function which asynchronously opens and reads a text file and write the lines into a vector. I am recieving an Access Violation. Why?
Windows::Foundation::Collections::IVector<Platform::String^>^ FileHandler::readFileReturnVectorWithLines(Platform::String^ filename)
{
Windows::Foundation::Collections::IVector<Platform::String^>^ vector_of_lines;
Windows::ApplicationModel::Package^ package = Windows::ApplicationModel::Package::Current;
Windows::Storage::StorageFolder^ installedLocation = package->InstalledLocation;
create_task(installedLocation->GetFileAsync(filename)).then([&vector_of_lines](Windows::Storage::StorageFile^ file)
{
return FileIO::ReadLinesAsync(file);
}).then([&vector_of_lines](Windows::Foundation::Collections::IVector<Platform::String^>^ lines)
{
// The following line produces an access violation!
vector_of_lines = lines;
});
return vector_of_lines;
}
推荐答案
您正在捕获"vector_of_lines";通过引用,以及当"then"执行"vector_of_lines".参考不再有效.而是按值捕获,即"[vector_of_lines]".
You are capturing "vector_of_lines" by reference, and when the "then" is executed the "vector_of_lines" reference is no longer valid. Capture by value instead, i.e. "[vector_of_lines]".
此外,由于现在您的代码没有多大意义,因此您必须调用"wait"(等待).在返回"vector_of_lines"之前,在创建的任务上执行否则您应该返回任务< IVector< String ^>> ^>.现在,您正在返回的对象 不知道它是否有效(即异步任务是否仍在运行?).
Also, as it is now your code doesn't make much sense, either you have to call "wait" on the created task before returning "vector_of_lines" or you should return a task<IVector<String^>>^>. As it is now you are returning an object that you cannot know whether it is valid or not (i.e. is the asynchronous task still running or not?).
这篇关于ReadLinesAsync()产生访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!