C # - When I use the task :: wait () method, it throws an exception

I am programming a Windows Store application and I have the following problem. I use this code to write an array of numbers to a file:

auto item = KnownFolders::PicturesLibrary;
task<StorageFile^> getFileTask(item->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting));
getFileTask.then([=](StorageFile^ storageFile)
{
    return storageFile->OpenAsync(FileAccessMode::ReadWrite);
}).then([](IRandomAccessStream^ m_istream)mutable
{
    unsigned char a[] = { 1, 2, 3 };
    auto arr = ref new Array<unsigned char>(a, sizeof(a));
    auto outs = m_istream->GetOutputStreamAt(0);
    auto dw = ref new DataWriter(outs);
    dw->WriteBytes(arr);
    return dw->StoreAsync();
}).wait();

The code compiled successfully, but it provides an error: MyTest.exe caused a breakpoint. And he points to the line _REPORT_PPLTASK_UNOBSERVED_EXCEPTION();that is in ppltasks.h.

If I use .then([](DataWriterStoreOperation^){})instead .wait(), My application does not compile with this error:

error C2338: incorrect parameter type for the callable object in 'then'; 
consider _ExpectedParameterType or task<_ExpectedParameterType> (see below).

Why? I am using VS2013. Please help me.

+4
source share
1 answer

I found a solution to this problem !!! Right code:

unsigned char a[] = { 1, 2, 3 };
auto arr = ref new Array<unsigned char>(a, sizeof(a));
auto m_istream = ref new InMemoryRandomAccessStream();
auto outs = m_istream->GetOutputStreamAt(0);
auto dw = ref new DataWriter(outs);
dw->WriteBytes(arr);
task<unsigned int>(dw->StoreAsync()).then([=](unsigned int)
{
    return item->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting);
}).then([=](StorageFile^ storageFile)
{
    return storageFile->OpenAsync(FileAccessMode::ReadWrite);
}).then([=](IRandomAccessStream^ new_stream)
{
    return RandomAccessStream::CopyAsync(m_istream->GetInputStreamAt(0), new_stream->GetOutputStreamAt(0));
}).then([=](UINT64 copiedBytes)
{
    return;
});
+2
source

Source: https://habr.com/ru/post/1526493/


All Articles