Say I have the following method that subscribes to an event. A callback is called when the event occurs. I would like to prevent my method to return until the callback is called, or after 10 seconds has passed.
public async Task<string> GetImportantString()
{
string importantResult = null;
await SubscribeToEvent("some event", async (message) =>
{
importantResult = message; // When "some event" happens, callback is called and we can set importantResult
}
return message; // Only return when the callback is called, or 10 seconds have passed
}
The signature for SubscribeToEvent()
is as follows:
public Task SubscribeToEvent(string event, Action<string> handler);
The way I would use method GetImportantString()
is as follows:
public void SomeMethod()
{
// Do some things
var importantString = await GetImportantString();
// Do other things
}
The problem is that I cannot find a way to not return from GetImportantString()
until the callback has been called. Ideally, I would like to wait until the callback has called for up to 10 seconds and return an error if the callback was not called within 10 seconds. How can I suspend the execution of GetImportantString()
until a callback is called?