Why does my C++/WinRT program with an IAsyncOperation take 2 seconds longer if I remove system("");?

157 Views Asked by At

I have written a short C++ program that uses the WinRT Geolocation API to print the user's location to the console. Here's a minimal working excerpt:

#include <winrt/Windows.Devices.Geolocation.h>
#include <winrt/Windows.Foundation.Collections.h>

using namespace winrt::Windows::Devices::Geolocation;
using namespace winrt::Windows::Foundation;

IAsyncOperation<Geoposition> get_location() {
    Geolocator geolocator;
    co_return co_await geolocator.GetGeopositionAsync();
}

int main(void) {
    double lat, lon;
    {
        winrt::init_apartment();
        Geoposition pos = get_location().get();
        lat = pos.Coordinate().Point().Position().Latitude;
        lon = pos.Coordinate().Point().Position().Longitude;
    }
    winrt::uninit_apartment();
    printf("%.15g\n", lat);
    printf("%.15g\n", lon);
//    system("");
    return 0;
}

This program, compiled as written here, works (given the user has enabled desktop app access to location in their privacy settings), but about 80% of the time it waits for almost exactly 2 seconds after printing both lines but before exiting. I do not know if this pause is due to IAsyncOperation, Geolocator, or something else.

In the course of testing possible fixes, I have found that simply adding system(""); immediately before the return statement seems to entirely eliminate the pause. Why is this? It feels like a hacky workaround; how can I address the underlying problem directly? Is there anything else I should do to pinpoint the issue?

Other things I've tried:

  • Using std::cout << pos... << std:endl; makes no difference
  • Adding fflush(stdout); makes no difference
  • Replacing printf("%.4f\n", pos...) with printf("%.4f\n", 0.1234) makes no difference
  • Removing the inner block in main() eliminates the pause
  • Running in cmd vs powershell vs wsl makes no difference
  • Building with /Od vs /O2 makes no difference
  • Building for x86 vs x64 makes no difference

I am compiling with /std:c++20 in Visual Studio 2022 17.8.6 using C++/WinRT 2.0.240111.5.

0

There are 0 best solutions below