Skip to content

Instantly share code, notes, and snippets.

@JaiganeshKumaran
Created July 30, 2022 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaiganeshKumaran/bddaeab4b114d114db78d7e6153e9e3f to your computer and use it in GitHub Desktop.
Save JaiganeshKumaran/bddaeab4b114d114db78d7e6153e9e3f to your computer and use it in GitHub Desktop.
Create a fake async operation that returns a result immediately when invoked
```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