I have a function, let's call it Func1 and it contains
Func2 & event handler.
Now what I would like to achieve is not let
function (Func1) return value till Func2 fires and handles event.
Basically Func1 has string as return value and string value is set inside event handler. So I need to wait for event to be handled and then return value.
Code Example
public static string Fun1 ()
{
string stringToReturn = String.Empty;
Func2(); //Func2 will after few sec fire event bellow
example.MyEvent += (object sender, WebBrowserDocumentCompletedEventArgs e) =>
{
stringToReturn = "example"; //this wont be hardcoded
};
//wait for event to be handled and then return value
return stringToReturn;
}
You could use the AutoResetEvent
class. Instantiate it with var evt = new AutoResetEvent(false);
, call evt.WaitOne()
where you want to wait, and evt.Set();
where you want to signal that the waiting code may proceed.
If you have many "wait until" situations that involve events, you could also look into Reactive Extensions (Rx).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With