Wait inside method until event is captured

后端 未结 3 1817
心在旅途
心在旅途 2021-01-02 02:45

I have this issue with a method in C#. I made a method that calls a function from a dll its called Phone.GetLampMode(); Now Phone.GetLampMode doesn

3条回答
  •  萌比男神i
    2021-01-02 03:36

    One solution is to use 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();
    }
    

    NOTE: Ad you're using Phone as a static class/variable, one can think you're developing on Windows Phone... If it is the case, do note that the whole concept of WP and async programming is to not lock the UI thread in a such way.

提交回复
热议问题