locked
ref class and it's asynchronous function

    Question

  • There is a ref class named RefClassA, it has a member function named fun1(). In fun1(), It calls a asynchronous function such as MusicLibrary->CreateFileAsync().

    public ref class RefClassA
    {
    public:
        RefClassA();
        ~RefClassA();
    
        void fun1()
        {
            task<SotrageFile^>(MusicLibrary->CreateFileAsync("sample.txt")).then([this](..))
               {
                  //some code
               }
        }
    };

    when I use it like this:

    void A()
    {
        RefClassA ^test = ref new RefClassA();
         test->fun1();
    }

    as mentioned in C++/CX, when object "test" goes out of scope, it mat be freed. 

    My question is that, does C++/CX make sure that the object "test" would be freed after the callback of "CreateFileAsync"?

    Friday, March 30, 2012 3:33 AM

Answers

  • Yes. If you are familiar with COM semantics, the ref new will create the object and add a reference count. Passing the this reference into the task will add another reference count. Leaving scope of A will decrement the ref count, and leaving scope of the continuation will decrement the refcount to 0 and the object will be cleaned up.

    -Steve

    Friday, March 30, 2012 6:20 PM
    Moderator

All replies

  • Yes. If you are familiar with COM semantics, the ref new will create the object and add a reference count. Passing the this reference into the task will add another reference count. Leaving scope of A will decrement the ref count, and leaving scope of the continuation will decrement the refcount to 0 and the object will be cleaned up.

    -Steve

    Friday, March 30, 2012 6:20 PM
    Moderator
  • Thank you very much!
    Saturday, March 31, 2012 1:50 AM