Created
September 27, 2012 03:55
-
-
Save ejball/3792072 to your computer and use it in GitHub Desktop.
Async unit tests in C++/Cx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
T WaitForTask(concurrency::task<T> t) | |
{ | |
Windows::UI::Core::CoreDispatcher^ dispatcher = | |
Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher; | |
HANDLE hEvent = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS); | |
if (hEvent == NULL) | |
throw std::bad_alloc(); | |
T result; | |
bool exceptionHandled = false; | |
std::wstring exceptionMessage; | |
t.then([&hEvent, &exceptionHandled, &exceptionMessage, &result](concurrency::task<T> previousTask){ | |
try | |
{ | |
result = previousTask.get(); | |
} | |
catch (Platform::Exception^ ex) | |
{ | |
exceptionHandled = true; | |
exceptionMessage = std::wstring(ex->Message->Data()); | |
} | |
catch (std::exception & ex) | |
{ | |
exceptionHandled = true; | |
exceptionMessage = std::wstring(ex.what(), ex.what() + strlen(ex.what())); | |
} | |
catch (...) | |
{ | |
exceptionHandled = true; | |
exceptionMessage = std::wstring(L"Unrecognized C++ exception."); | |
} | |
SetEvent(hEvent); | |
}, concurrency::task_continuation_context::use_arbitrary()); | |
DWORD waitResult = STATUS_PENDING; | |
while (waitResult != WAIT_OBJECT_0) | |
{ | |
dispatcher->ProcessEvents(Windows::UI::Core::CoreProcessEventsOption::ProcessAllIfPresent); | |
waitResult = WaitForSingleObjectEx(hEvent, 0, TRUE); | |
} | |
CloseHandle(hEvent); | |
if (exceptionHandled) | |
Microsoft::VisualStudio::CppUnitTestFramework::Assert::Fail(exceptionMessage.c_str()); | |
return result; | |
} | |
template<> | |
inline void WaitForTask<void>(concurrency::task<void> t) | |
{ | |
WaitForTask(t.then([]{ return true; })); | |
} | |
template <typename T> | |
inline T WaitForTask(Windows::Foundation::IAsyncOperation<T>^ t) | |
{ | |
return WaitForTask(concurrency::task<T>(t)); | |
} | |
inline void WaitForTask(Windows::Foundation::IAsyncAction^ t) | |
{ | |
return WaitForTask(concurrency::task<void>(t)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment