Using Win11; VS2019; C++; SDK 10.0.22621.0; Platform Toolset VS 2019; C++ Language Standard C++17; NuGet CppWinRT 2.0.220608.4
Normally, if I have a process that I want to send off to complete on its own, I start a std::thread and then detach it like this:
std::thread FindBleDeviceThread(FindBleDevice);
FindBleDeviceThread.detach();
In this case, however, I see -- maybe I am only noticing this for the first time -- that the code in the FindBleDevice function does not even start until after I leave the current calling function to briefly go to a DialogBox. Maybe this is normal behavior and I had just never noticed the delay before.
In this case the FindBleDevice is a function using C++/WinRT code to start a watcher to look for a specific Bluetooth LE device and, once it is found, to call a separate function to Open it.
void FindBleDevice() {
bDeviceOpened = false; // This first line never starts until the DialogBox is called.
// Find device code here
OpenDevice(deviceAddress); // IAsyncAction function
return;
}
The OpenDevice function is:
winrt::Windows::Foundation::IAsyncAction OpenDevice(unsigned long long deviceAddress){
auto device = co_await BluetoothLEDevice::FromBluetoothAddressAsync(deviceAddress);
// More code here to get GATT Services and Characteristics and do a few writes to the Tx characteristic.
}
The call to FindBleDevice is within a function which was called from the app's main thread. The FindBleDevice thread is started and detached and nothing happens in the FindBleDevice code (not even the first line of code) until a DialogBox is called getting us briefly out of the function that called the thread.
What am I missing here? Why would that FindBleDevice thread not run on it's own as I would expect but instead wait until we are out of the calling function?