Wait inside method until event is captured

后端 未结 3 1818
心在旅途
心在旅途 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:42

    You can wrap the handler in an asynchronous method, which should look something like this (untested):

    public async Task checkLamp(int iLamp)
    {
        Phone.ButtonIDConstants btn = new Phone.ButtonIDConstants();
        btn = Phone.ButtonIDConstants.BUTTON_1;
        btn += iLamp;
    
        var tcs = new TaskCompletionSource();
        var handler = (sender, e) => {
            Phone.OnGetLampModeResponse -= handler;
            var test = e.getLampModeList[0].getLampMode.ToString();
            tcs.SetResult(true);
        };
        Phone.OnGetLampModeResponse += handler;
    
        Phone.GetLampMode(btn, null);
    
        return tcs.Task;
    }
    

    In your calling method, you would write:

    var returnValue = await checkLamp(iLamp);
    

    This has the advantage that your user interface does not block while the process is waiting for the response.

    Here's a blog entry on this issue. Note that Framework 4.5 is required.

    • http://blogs.msdn.com/b/lucian/archive/2012/11/28/how-to-await-a-button-click.aspx

提交回复
热议问题