c# asynchronous logic to synchronous call

Go To StackoverFlow.com

2

I have this

public Result SomeMethod()
{
    Popup popup = new Popup();

    popup.Closed += PopupClosedHandler;
    popup.ShowPopup();


    // have to return the result from handler.

}

void PopupClosedHandler(EventArgs<PopupEventArgs> args)
{
    Result result = args.Result;
}

I have to block SomeMethod() call until popup is called and return the Result from args in the handler. I have no idea how to do this or even how to look for it. Can anyone put me in the right direction? Thanks

2012-04-04 03:29
by Professor Chaos


3

You want to use an EventWaitHandle.

public Result SomeMethod()
{
    _doneHandler = new EventWaitHandle(false, EventResetMode.ManualReset);

    Popup popup = new Popup();

    popup.Closed += PopupClosedHandler;
    popup.ShowPopup();


    // This will wait until it is SET.  You can pass a TimeSpan 
    // so that you do not wait forever.
    _doneHandler.WaitOne();

   // Other stuff after the 'block'

}

private EventWaitHandle _doneHandler;

void PopupClosedHandler(EventArgs<PopupEventArgs> args)
{
    Result result = args.Result;

    _doneHandler.Set();
}
2012-04-04 03:45
by David Basarab
Perfect! Thank - Professor Chaos 2012-04-04 03:49


0

This is crude, but should give the general idea

public Result SomeMethod()
{
    Popup popup = new Popup();
    bool called = false;
    Result result = null;
    popup.Closed += (args) => {
        called = true;
        result = args.Result;
    }
    while(!called) ;
    return result;
}
2012-04-04 03:38
by Foran
Ads