How to block an async method till completion

Harikrishnan V R 21 Reputation points
2021-05-04T15:11:57.103+00:00

I have a fire_and_forget method,

fire_and_forget DeviceInfo::Connect()
{

// Pair
DevicePairingResult result = co_await GetDevice().Pairing().PairAsync();

// Connect
m_BluetoothLEDevice = co_await BluetoothLEDevice::FromIdAsync(GetId());

}

I need to come out from this fire_and_forget function after completing all the async methods inside

Please suggest some ideas

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
2,622 questions
No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jeanine Zhang-MSFT 4,891 Reputation points Microsoft Employee
    2021-05-05T02:45:29.347+00:00

    Hi,

    I suggest you could try to construct a mutex object, by std::mutex, and then call the member function lock() to lock the mutex, call the member function unlock() to unlock it. You could also try to use lock_guard Class.

    And then you could use the condition_variable class to wait for an event when you have a mutex of type unique_lock<mutex>. You only need to call wait and notify_one.

    Best Regards,

    Jeanine


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.