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


  • 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
    var class1 = new
        var asyncOp = await class1.DoSomeTaskAsync().AsTask(tcs.Token);
    catch (OperationCanceledException oce)
        //I want to get here

    From C++:

            return concurrency::create_async([](concurrency::cancellation_token ct)
                task<bool> my_task([]()
    if (concurrency::is_task_cancellation_requested())
    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
  • 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