Waiting for an event to process

I have a function, call it Func1 and it containsFunc2 and an event handler.

Now, what I would like to get is not letfunction (Func1) to return the value until Func2 lights up and processes the event.

Basically Func1 has a string as the return value, and the string value is set inside the event handler. So I need to wait for the event to be processed, and then return the 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;
    }
+5
source share
3 answers

AutoResetEvent. var evt = new AutoResetEvent(false);, evt.WaitOne(), , evt.Set();, , .

, , Reactive Extensions (Rx).

+8

?

public static string Fun1 ()
{
    Semaphore sem = new Semaphore(1,1);

    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
                               sem.Release();
                           };
    sem.WaitOne();

    //wait for event to be handled and then return value
    return stringToReturn;
}
+1

Func2 , Func1, Func1 Func2. , , , Func2, , Func1. Func2 .

Using Semaphoreeither AutoResetEventin this scenario is excessive because both acquire OS resources to control thread synchronization.

0
source

All Articles