Updating UI from events using asyc await

前端 未结 4 1495
北海茫月
北海茫月 2020-12-31 00:16

I am trying to understand how to update a UI from an event while using async/await pattern. Below is the test code I am using on a WinForm app. I am not even sure this is th

4条回答
  •  猫巷女王i
    2020-12-31 00:51

    You should use Invoke method of Control. It executes some code in Control's thread. Also you can check InvokeRequired property to check if you need to call Invoke method (it checks if the caller is on a different thread than the one the control was created on).

    Simple example:

    void SomeAsyncMethod()
    {
        // Do some work             
    
        if (this.InvokeRequired)
        {
            this.Invoke((MethodInvoker)(() =>
                {
                    DoUpdateUI();
    
                }
            ));
        }
        else
        {
            DoUpdateUI();
        }
    }
    
    void DoUpdateUI()
    {
        // Your UI update code here
    }
    

    In some cases you should check the IsHandleCreated property of Control before calling Invoke method. If IsHandleCreated returns false then you need wait while Control's handle will be created

提交回复
热议问题