Toni
Toni

Reputation: 51

Waiting for event to be handled

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;
    }

Upvotes: 5

Views: 5996

Answers (3)

Florian Greinacher
Florian Greinacher

Reputation: 14784

As Func2 runs on the same thread as Func1, Func1 will not return before Func2 returns. This means it is guaranteed that the event fired in Func2 is getting fired before it returns control to Func1. Just attach your event handler before calling Func2 and it should work as expected.

Using a Semaphore or an AutoResetEvent is overkill in this scenario as both acquire OS resources to manage thread synchronization.

Upvotes: 0

DanTheMan
DanTheMan

Reputation: 3277

Wouldn't a simple semaphore suffice?

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;
}

Upvotes: 1

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 38010

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

Upvotes: 8

Related Questions