Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for event to be handled

Tags:

c#

events

wait

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;
    }
like image 836
Toni Avatar asked Jul 07 '11 17:07

Toni


1 Answers

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).

like image 79
Aasmund Eldhuset Avatar answered Sep 25 '22 22:09

Aasmund Eldhuset