locked
How do you cancel an async operation in C++/CX from C#

    Question

  • I'm trying to cancel an operation that is written in C++/CX from C#.  Despite the fact I wrote both pieces of code I can't get the operation to cancel properly when awaiting it from the C# side.  Here's an example:

    From C#:

    var tcs = new
    CancellationTokenSource();
    tcs.Cancel();
    var class1 = new
    MyClass();
    try
    {
        var asyncOp = await class1.DoSomeTaskAsync().AsTask(tcs.Token);
    }
    catch (OperationCanceledException oce)
    {
        //I want to get here
        Handle(oce);
    }

    From C++:

    IAsyncOperation<bool>^
    MyClass::DoSomeTaskAsync(){
            return concurrency::create_async([](concurrency::cancellation_token ct)
    {
                task<bool> my_task([]()
    {
                    doSomething1();
                   
    if (concurrency::is_task_cancellation_requested())
                   
    {
                        concurrency::cancel_current_task();
                   
    }
                    doSomething2();
                   
    return false;
                }, ct);
                return my_task;
            });
        }

    The problem seems to be that passing in the token into the AsTask extension method does nothing when calling a task across the ABI.  When debugging the C++ side both the ct and the is_task_cancellation_requested() function indicate that a cancellation has not been requested.


    • Edited by Kellen Thursday, February 6, 2014 6:52 PM
    Thursday, February 6, 2014 6:51 PM

All replies

  • This isn't an area that I'm really familiar with, but let's see if we can work through this together.

    Are you expecting that the cancelled task automatically throws the OperationCancelledException?  What happens if you explicitly throw the exception?


    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Monday, February 10, 2014 2:00 PM
    Moderator
  • See Creating Asynchronous Operations in C++ for Windows Store Apps for a code example and explanation as well. Look under the heading "Example: Creating a C++ Windows Runtime Component and Consuming it from C#".

    Tuesday, February 18, 2014 8:49 PM