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.
3,969 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jeanine Zhang-MSFT 11,351 Reputation points Microsoft External Staff
    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.