我有点绝望地试图获得带有Windows::Foundation::IAsyncOperation
接口的 winrt 异步方法的结果。该项目是一个启用了 winRT 扩展的 Visual Studio Community 2017 c++ 项目。 我尝试使用std::future
/co_await
函数和任务方法,但对GetResults()
调用总是"在意外时间调用"异常。
使用以下代码,我没有得到异常,但GetResults()
返回nullptr
.我还尝试将async_op
声明为shared_ptr
auto async_op = std::make_shared<Windows::Foundation::IAsyncOperation<Windows::Devices::Bluetooth::BluetoothLEDevice^> ^>
并使用Handler
代码中的*async_op
访问它,但我得到了相同的结果。
欢迎任何想法。
提前谢谢。
void BleEnumeration::PerformConnectDevice(std::string* bleDevId)
{
std::wstring bleDevId_w_str = std::wstring((*bleDevId).begin(), (*bleDevId).end());
const wchar_t* bleDevId_w_char = bleDevId_w_str.c_str();
Platform::String^ bleDevId_refStr = ref new Platform::String(bleDevId_w_char);
auto async_op = Windows::Devices::Bluetooth::BluetoothLEDevice::FromIdAsync(bleDevId_refStr);
async_op->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::BluetoothLEDevice^>(
[async_op] (Windows::Foundation::IAsyncOperation< Windows::Devices::Bluetooth::BluetoothLEDevice^ >^ operation, Windows::Foundation::AsyncStatus status)
{
if (async_op->Status == Windows::Foundation::AsyncStatus::Completed)
{
auto bleDevTest = async_op->GetResults();
}
});
}
我让它工作了:
Windows::Devices::Bluetooth::BluetoothLEDevice^ BleEnumeration::getBleDevice(Windows::Foundation::IAsyncOperation<Windows::Devices::Bluetooth::BluetoothLEDevice^>^ async)
{
if ((async)->Status != Windows::Foundation::AsyncStatus::Completed)
{
HANDLE signal = CreateEvent(nullptr, true, false, nullptr);
(async)->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::BluetoothLEDevice^>(
[&signal](Windows::Foundation::IAsyncOperation< Windows::Devices::Bluetooth::BluetoothLEDevice^ >^ operation, Windows::Foundation::AsyncStatus status)
{
SetEvent(signal);
});
WaitForSingleObject(signal, INFINITE);
}
Windows::Devices::Bluetooth::BluetoothLEDevice^ device = async->GetResults();
return device;
}
bool BleEnumeration::PerformConnectDevice(std::string* bleDevId)
{
bool success = false;
Windows::Devices::Bluetooth::BluetoothLEDevice^ bleDevTest = nullptr;
std::wstring bleDevId_w_str = std::wstring((*bleDevId).begin(), (*bleDevId).end());
const wchar_t* bleDevId_w_char = bleDevId_w_str.c_str();
Platform::String^ bleDevId_refStr = ref new Platform::String(bleDevId_w_char);
Windows::Foundation::IAsyncOperation<Windows::Devices::Bluetooth::BluetoothLEDevice^>^ asyncOp = Windows::Devices::Bluetooth::BluetoothLEDevice::FromIdAsync(bleDevId_refStr);
bleDevTest = getBleDevice(asyncOp);
if (bleDevTest != nullptr)
{
success = true;
}
return success;
}
而且,GetResults(( 给出 nullptr 的原因是:在 appxmanifest 中启用功能
所有需要的功能都必须在Visual Studio项目Package.appxmanifest文件中启用,在我的例子中是:"蓝牙"。我注意到我收到错误:onecoreuapdriverswdmbluetoothuserwinrtdevicebluetoothledevice.cpp(728)Windows.Devices.Bluetooth.dll!00007FFC1601AE2F: (caller: 00007FFC1602081A) Exception(1) tid(212c) 80070005 Access is denied.