等待内部方法直到捕获事件

Jen*_*ait 11 c# events wait

我在C#中遇到了这个问题.我做了一个方法,从一个dll调用一个函数,它被称为Phone.GetLampMode(); Now Phone.GetLampMode并不返回任何东西.在' onGetLampModeResponse'事件中返回数据.有没有办法可以在我的方法中等待,直到我从onGetLampModeResponse事件中获取数据?

public bool checkLamp(int iLamp)
{
    Phone.ButtonIDConstants btn = new Phone.ButtonIDConstants();
    btn = Phone.ButtonIDConstants.BUTTON_1;
    btn += iLamp;
    Phone.GetLampMode(btn, null);

    return true;
}

private void Phone_OnGetLampModeResponse(object sender, Phone.GetLampModeResponseArgs e)
{
    var test = e.getLampModeList[0].getLampMode.ToString();    
}
Run Code Online (Sandbox Code Playgroud)

ken*_*n2k 9

一种解决方案是使用AutoResetEvent:

public bool checkLamp(int iLamp)
{
    Phone.ButtonIDConstants btn = new Phone.ButtonIDConstants();
    btn = Phone.ButtonIDConstants.BUTTON_1;
    btn += iLamp;

    AutoResetEvent waitHandle = new AutoResetEvent(false); 

    // Pass waitHandle as user state
    Phone.GetLampMode(btn, waitHandle);

    // Wait for event completion
    waitHandle.WaitOne();

    return true;
}

private void Phone_OnGetLampModeResponse(object sender, Phone.GetLampModeResponseArgs e)
{
    var test = e.getLampModeList[0].getLampMode.ToString();

    // Event handler completed
    // I guess there is some UserState property in the GetLampModeResponseArgs class
    ((AutoResetEvent)e.UserState).Set();
}
Run Code Online (Sandbox Code Playgroud)

注意:您正在使用的广告Phone作为静态类/变量,可以认为您正在开发Windows Phone ...如果是这样,请注意WP和异步编程的整个概念是不锁定UI以这种方式穿线.

  • 你刚刚把waitHandle放到了全局环境中吗?如果你不止一次执行它并让你的等待完全卡住怎么办?这个答案怎么能得到提升呢? (2认同)