2015-10-16 62 views
1

我有以下代碼可以打開一個文件,並且它大部分時間都可以運行一次。之後,我得到異常拋出,我不知道問題隱藏在哪裏。我已經嘗試了幾天,但沒有運氣。C++/CX - DataReader超出範圍例外

String^ xmlFile = "Assets\\TheXmlFile.xml"; 
xml = ref new XmlDocument(); 
StorageFolder^ InstallationFolder = Windows::ApplicationModel::Package::Current->InstalledLocation; 
task<StorageFile^>(
InstallationFolder->GetFileAsync(xmlFile)).then([this](StorageFile^ file) { 
    if (nullptr != file) { 
     task<Streams::IRandomAccessStream^>(file->OpenAsync(FileAccessMode::Read)).then([this](Streams::IRandomAccessStream^ stream) 
     { 
      IInputStream^ deInputStream = stream->GetInputStreamAt(0); 
      DataReader^ reader = ref new DataReader(deInputStream); 
      reader->InputStreamOptions = InputStreamOptions::Partial; 
      reader->LoadAsync(stream->Size); 

      strXml = reader->ReadString(stream->Size); 

      MessageDialog^ dlg = ref new MessageDialog(strXml); 
      dlg->ShowAsync();  
     }); 
    } 
}); 

錯誤觸發在這部分代碼:

strXml = reader->ReadString(stream->Size); 

我收到以下錯誤:

First-chance exception at 0x751F5B68 in XmlProject.exe: Microsoft C++ exception: Platform::OutOfBoundsException^at memory location 0x02FCD634. HRESULT:0x8000000B The operation attempted to access data outside the valid range

WinRT的信息:操作試圖超出了有效訪問數據範圍

就像我說的,它第一次正常工作,但之後,我得到了呃ROR。我嘗試分離datareader的流和緩衝區,並試圖刷新流,但沒有結果。

回答

0

我也在Microsoft C++論壇上問過這個問題,並在user「Viorel_」上寫道,我設法讓它工作。維奧雷爾下面說:

Since LoadAsync does not perform the operation immediately, you should probably add a corresponding 「.then」. See some code: https://social.msdn.microsoft.com/Forums/windowsapps/en-US/94fa9636-5cc7-4089-8dcf-7aa8465b8047 . This sample uses 「create_task」 and 「then」: https://code.msdn.microsoft.com/vstudio/StreamSocket-Sample-8c573931/sourcecode (file Scenario1.xaml.cpp, for example).

我不得不在task<Streams::IRandomAccessStream^>內容分開和獨立的任務分裂它。

我重建我的代碼,我現在有以下幾點:

String^ xmlFile = "Assets\\TheXmlFile.xml"; 
xml = ref new XmlDocument(); 
StorageFolder^ InstallationFolder = Windows::ApplicationModel::Package::Current->InstalledLocation; 
task<StorageFile^>(
InstallationFolder->GetFileAsync(xmlFile)).then([this](StorageFile^ file) { 
    if (nullptr != file) { 
     task<Streams::IRandomAccessStream^>(file->OpenAsync(FileAccessMode::Read)).then([this](Streams::IRandomAccessStream^ stream) 
     { 
      IInputStream^ deInputStream = stream->GetInputStreamAt(0); 
      DataReader^ reader = ref new DataReader(deInputStream); 
      reader->InputStreamOptions = InputStreamOptions::Partial; 
      create_task(reader->LoadAsync(stream->Size)).then([reader, stream](unsigned int size){     
       strXml = reader->ReadString(stream->Size); 
       MessageDialog^ dlg = ref new MessageDialog(strXml); 
       dlg->ShowAsync(); 
      });    
     }); 
    } 
});