Created
July 30, 2022 05:56
-
-
Save jaigak/bddaeab4b114d114db78d7e6153e9e3f to your computer and use it in GitHub Desktop.
Create a fake async operation that returns a result immediately when invoked
This file contains hidden or 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
```cpp | |
// Can be used in a similar way to .NET's Task.FromResult and PPL's concurrency::create_async (See https://github.com/microsoft/cppwinrt/issues/1036). | |
template <typename Result> | |
struct AsyncOperationWrapper : implements<AsyncOperationWrapper<Result>, Windows::Foundation::IAsyncOperation<Result>> | |
{ | |
public: | |
AsyncOperationWrapper(Result result) : m_Result(result) {} | |
auto Id() const noexcept | |
{ | |
return juv::as_value<juv::uint32>(this); | |
} | |
auto ErrorCode() const noexcept | |
{ | |
return hresult(0); | |
} | |
auto Status() const noexcept | |
{ | |
return Windows::Foundation::AsyncStatus::Completed; | |
} | |
auto Completed() const noexcept | |
{ | |
return m_Completed; | |
} | |
void Completed(Windows::Foundation::AsyncOperationCompletedHandler<Result> const& value) | |
{ | |
value(*this, Windows::Foundation::AsyncStatus::Completed); | |
m_Completed = value; | |
} | |
auto GetResults() const noexcept | |
{ | |
return m_Result; | |
} | |
void Cancel() const noexcept {} | |
void Close() const noexcept {} | |
private: | |
Result m_Result; | |
Windows::Foundation::AsyncOperationCompletedHandler<Result> m_Completed; | |
}; | |
``` | |
Usage: ```cpp | |
IAsyncOperation<SomeType> operation = make<AsyncOperationWrapper<SomeType>>(SomeValue); | |
auto result = co_await operation; | |
// The value held by result should be equal to the original value you specified while constructing AsyncOperationWrapper<SomeType>. | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment