February 15th, 2022

COM asynchronous interfaces, part 2: Abandoning the operation

Last time, we ran a very basic demonstration of COM asynchronous interfaces. Now we’ll start to get fancy.

Our first fancy thing is creating a fire-and-forget asynchronous call. To do this, you simply abandon the call object after calling the Begin_ method. It means that you never find out the answer, or even learn that it failed. But if you were going to ignore the result anyway, then it doesn’t matter.

int main(int, char**)
{
  winrt::init_apartment(winrt::apartment_type::multi_threaded);

  auto pipe = CreateSlowPipeOnOtherThread();

  winrt::com_ptr<::AsyncIPipeByte> call;
  auto factory = pipe.as<ICallFactory>();
  winrt::check_hresult(factory->CreateCall(
    __uuidof(::AsyncIPipeByte), nullptr,
    __uuidof(::AsyncIPipeByte),
    reinterpret_cast<::IUnknown**>(call.put())));

  printf("Beginning the Push\n");
  BYTE buffer[15] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                      11, 12, 13, 14, 15 };
  winrt::check_hresult(call->Begin_Push(buffer, 15));

  call = nullptr; // throw it away!
  printf("Abandoned the call\n");

  Sleep(5000); // just so you can see the other thread
  return 0;
}

After initiating a Push with Begin_Push, we simply release the call object (which happens when we set it to nullptr) and go on with our lives. The call is still running, but we have lost our ability to access its results.

If you run this program, you can see that the call to Push continues running to completion. Depending on the timing, you may even observe the call become abandoned before the Push method even starts!

Next time, we’ll abandon the operation only if it takes too long.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Henke37

    You may even what? I think you accidentally a word there.