VladVin
VladVin

Reputation: 643

C# - When I use task::wait() method it throwing the exception

I programming Windows Store App, and I have following problem. I use this code to record the 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();

Code is successfully compiled, but it provide an error: MyTest.exe has triggered a breakpoint. And it point to _REPORT_PPLTASK_UNOBSERVED_EXCEPTION(); line, that be found in ppltasks.h.

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

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

Why is that? I using VS2013. Please help me.

Upvotes: 4

Views: 1174

Answers (1)

VladVin
VladVin

Reputation: 643

I found the solution of 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;
});

Upvotes: 2

Related Questions