2009-08-21 87 views
1

我的目標是在函數「虛擬」我可以改變控制像標籤等形式的線程正在啓​​動..如何做到這一點..請不要暗示完全如果你能C#線程 - 父訪問問題

 Thread pt= new Thread(new ParameterizedThreadStart(Dummy2)); 


     private void button1_Click(object sender, EventArgs e) 
     {      
      pt = new Thread(new ParameterizedThreadStart(Dummy2)); 
      pt.IsBackground = true; 
      pt.Start(this); 
     } 


     public static void Dummy(........) 
     { 
      /*     
      what i want to do here is to access the controls on my form form where the 
      tread was initiated and change them directly 
      */ 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      if (t.IsAlive) 
       label1.Text = "Running"; 
      else 
       label1.Text = "Dead"; 
     } 

     private void button3_Click(object sender, EventArgs e) 
     { 
      pt.Abort(); 
     } 


    } 
} 

什麼,我的計劃是,我可以在「虛擬」功能做到這一點

Dummy(object p) 
{ 
    p.label1.Text = " New Text " ; 
} 

回答

4

你能做到這一點,假設你使用的t.Start(...)方法傳遞形式的實例,以線程方式:

private void Form_Shown(object sender) 
{ 
    Thread t = new Thread(new ParameterizedThreadStart(Dummy)); 
    t.Start(this); 
} 

.... 


private static void Dummy(object state) 
{ 
    MyForm f = (MyForm)state; 

    f.Invoke((MethodInvoker)delegate() 
    { 
     f.label1.Text = " New Text "; 
    }); 
} 

編輯
爲清晰起見,添加了線程起始代碼。

+0

現在如果我想這樣做,這個線程做它應該做的事情,並且在每個「X」秒之後它一次又一次地喚醒 – Moon 2009-08-21 12:43:09

+0

這個「Invoke」將要花費多少內存,可以說如果父表單有很多用戶界面控件都是 – Moon 2009-08-21 12:45:19

+0

第一條評論:添加計時器以形成。如果線程尚未處於活動狀態並創建新線程(線程無法重用),則每隔X秒觸發一次,或者在線程方法中循環並執行完所需的操作之後:休眠X秒(必須先退出線程關閉窗體!!) – 2009-08-21 12:48:40

3

你不能做不同的策略,或使工人類等...修改此這個。您只能在創建它的相同線程上訪問UI控件。

查看System.Windows.Forms.Control.Invoke MethodControl.InvokeRequired屬性。

+0

你能給我一個例子:如何從「沒有創建它」的其他線程訪問UI控件 – Moon 2009-08-21 12:23:10

+1

你能點擊我提供的鏈接嗎? – 2009-08-21 12:47:17

2

可以使用這樣的事情:

private void UpdateText(string text) 
{ 
    // Check for cross thread violation, and deal with it if necessary 
    if (InvokeRequired) 
    { 
     Invoke(new Action<string>(UpdateText), new[] {text}); 
     return; 
    } 

    // What the update of the UI 
    label.Text = text; 
} 

public static void Dummy(........) 
{ 
    UpdateText("New text"); 
} 
+0

你在這裏調用Invoke和InvokeRequired? – Marc 2009-08-21 12:25:49

+0

有標籤的表單。 – Svish 2009-08-21 20:18:06