[MS] Making an agile version of a Windows Runtime delegate in C++/WinRT, part 4 - devamazonaws.blogspot.com
Last time, we wrote a wrapper delegate that checked whether the context it was being invoked from matched the context it was captured from . if (d.try_as<::INoMarshal>()) { return [d = std::forward<Delegate>(d), context = winrt::capture<IContextCallback>(CoGetObjectContext)](auto&&...args) { if (context == winrt::capture<IContextCallback>(CoGetObjectContext)) { d(std::forward<decltype(args)>(args)...); } else { throw winrt::hresult_error(CO_E_NOT_SUPPORTED); } }; } We did this by comparing context objects. This obtains the current object context in order to compare it with the original one, and that means an internal AddRef , and then we have to explicitly Release it. But there's a way to do this without having to obtain any objects. The CoGetContextToken function gives you an integer that uniquely identifies a live context ob...