Exception message thrown from C++/CX async method consumed in C# app

0

I am writing C++/CX WinRT library targeting Windows 8.1 which I want to consume from C# app.
If I throw exception from asynchronous method, exception message shown in C# app is wrong.

In WinRT library I have C++/CX code like:

IAsyncOperation<int>^ test()
{
    return create_async([]() -> int
    {
        throw ref new Platform::Exception(E_POINTER, "My message.");
    });
}

In C# app I have code like:

try
{
    await c.test();
}
catch (Exception ex)
{
    Debug.WriteLine("Exception message: {0}", ex.Message);
}

Output in debug mode is:

    WinRT information: My message.
    First-chance exception at 0x77692C1A in App1.exe: Microsoft C++ exception: Platform::Exception ^ at memory location 0x09A5E434. HRESULT:0x80004003 Invalid pointer
    WinRT information: My message.
    A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
    Exception message: Object reference not set to an instance of an object.

I know about this problem. However, that is solved for Windows 8.1 apps. I succeeded to pass my exception message from non-asynchronous method, but I can't get it working for asynchronous. Can anyone help me out with this?

c#
c++
asynchronous
windows-runtime
c++-cx
asked on Stack Overflow Apr 10, 2014 by Nikola Nikolic

2 Answers

0

If it is asynchronous, it means the function c.test() is executed in another thread, the thread can only catch the exception form its own, so you code won't work.

Instead using exception, you can use return code. Also in this MSDN article: Best Practices in Asynchronous Programming, the first thing it talks about is: Avoid Async Void.

answered on Stack Overflow Apr 10, 2014 by Matt
0

as per MSDN (https://msdn.microsoft.com/en-us/library/Hh750082.aspx)

Use create_async only when you have to create functionality that can be accessed > from another language or another Windows Runtime component. Use the task class > > directly when you know that the operation is both produced and consumed by C++ > > code in the same component.

Summary: Use create_async when it is to be consumed by another language. Use create_task when consumed by c++.

Hope this helps =)

answered on Stack Overflow Sep 10, 2015 by user3164339

User contributions licensed under CC BY-SA 3.0