WIN FORM 多線程更新UI(界面控件)


方法1,更新單個控件:
public  delegate  void ControlTextMethod(Control control,  string text);
private  void SetControlText(Control control,  string text)
{
     if ( this.InvokeRequired)
    {
        ControlTextMethod controlTextMethod =  new ControlTextMethod(SetControlText);
         this.Invoke(controlTextMethod,  new  object[] { control, text });
    }
     else
    {
        control.Text = text;
    }
}

需要更新控件的Text的地方,直接調用SetControlText方法就可以了。

 

方法2,使用“UIThread”:

public  void UIThread(MethodInvoker method)
{
     if ( this.InvokeRequired)
    {
         this.Invoke(method);
    }
     else
    {
        method.Invoke();
    }
}

public  void UpdateUI()
{
     this.UIThread( delegate
    {
         this.Label1.Text =  " msg1 ";
         this.Label2.Text =  " msg2 ";
    });
}

在需要更新界面的地方這么調用:this.UIThread(delegate{this.Label1.Text="msg1";...});。

 

方法3,在一個方法里集中更新多個控件:

public  void UpdateUI()
{
     if ( this.InvokeRequired)
    {
         this.Invoke( new MethodInvoker( delegate { UpdateUI(); }));
    }
     else
    {
         this.Label.Text =  " msg1 ";
         this.Labe2.Text =  " msg2 ";
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM