2012-04-04 108 views
2

我有這個C#異步邏輯同步調用

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

我必須阻止SomeMethod()調用,直到彈出被調用,並從args在處理程序返回Result。我不知道如何做到這一點,甚至不知道如何去尋找它。任何人都可以把我放在正確的方向嗎?由於

回答

3

你想用一個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(); 
} 
+1

完美!謝謝 – 2012-04-04 03:49:56

0

這是粗糙的,但應該給一般的想法

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