locked
Writing user-defines functions that return a task in C++ metro style app RRS feed

  • Question

  • Can someone please show me how one can write a user-defined function that return a task(for eg: returning an IAsyncOperation )? Just for a simple example, I would like to code a functions as follows

     task<String^>MainPage::GetStringVal()

       String^ str = ref new String( L"Hello" );
     //  how to return
    }

    I am returning a string and the function should be able to be called as a task. How should I specify the retun from this function.?


    Sunday, July 8, 2012 7:45 AM

Answers

  • The specific answer to your question is to use create_task, e.g:

    task<String^> GetStringVal()
    {
    	// http://msdn.microsoft.com/en-us/library/hh913025(v=vs.110).aspx
    	return create_task([]{ return ref new String(L"Hello"); });
    }

    However, I think you want to use the create_async, following the guidance here for creating asynchronous operations -- http://msdn.microsoft.com/en-us/library/windows/apps/hh750082.aspx

    IAsyncOperation<String^>^ GetStringValAsync()
    {
    	return create_async([]
    		{ 
    			for(int i=0; i<1E9; i++); // simulate time consuming operation
    			return ref new String(L"Hello"); 
    		});
    }


    And then it's usage (disregard any intellisense errors as you won't see these in release)

    	IAsyncOperation<String^>^ iao = GetStringValAsync();
    	task<String^> t = create_task(iao);
    	t.then( [](String^ str){ /* lambda continuation, do something with string */} );
    Ref: http://msdn.microsoft.com/en-us/library/windows/apps/Hh780559.aspx


    Monday, July 9, 2012 9:11 PM
    Moderator