2016-05-15 62 views
0

我有2個窗體運行在不同的線程上。 Form2將生成一個字符串,將其發送回form1並更新form1中的richtextbox。我從我的朋友那裏得到了代碼,但我不明白它的一部分。有關調用,調用和多線程的C#問題

能否請您給我解釋一下爲什麼我們需要的條件:

if (this.f1_rtb_01.InvokeRequired) { } 

什麼做2號線以下呢?

SetTextCallback d = new SetTextCallback(SetText); 
this.Invoke(d, new object[] { text }); 

完整的代碼Form1中:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Threading; 

namespace PassingData2Forms 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    public string str_1; 

    private void call_form_2() 
    { 
     for (int i = 0; i < 10; i++) 
     { 
      Form2 inst_form2 = new Form2(); 
      inst_form2.ShowDialog(); 

      string result = inst_form2.SelectedString; 
      this.SetText(result); 
     } 
    } 

    delegate void SetTextCallback(string text); 

    private void SetText(string text) 
    { 
     if (this.f1_rtb_01.InvokeRequired) 
     { 
      SetTextCallback d = new SetTextCallback(SetText); 
      this.Invoke(d, new object[] { text }); 
     } 
     else 
     { 
      if (text != "") 
      { 
       this.f1_rtb_01.AppendText(text + Environment.NewLine); 
      } 
      else 
      { 
       this.f1_rtb_01.AppendText("N/A" + Environment.NewLine); 
      } 
     } 
    } 

    private void f1_but_01_Click(object sender, EventArgs e) 
    { 
     Thread extra_thread_01 = new Thread(() => call_form_2()); 
     extra_thread_01.Start();    
    } 
} 
} 
+1

你爲什麼在兩個線程上運行兩個窗體? –

回答

1

這部分:

SetTextCallback d = new SetTextCallback(SetText); 
this.Invoke(d, new object[] { text }); 

使電流形式來調用SetTextCallback委託的實例,傳遞變量text作爲參數。代表實例指向SetText()方法,由於調用this.Invoke(),該方法將在與窗體相同的線程上執行。

調用用於將代碼的執行從後臺線程移動到窗體的/控件的線程,從而使執行線程安全。

這部分僅僅是如果你需要調用檢查:

if (this.f1_rtb_01.InvokeRequired) 

如果您不需要調用這意味着代碼已經運行在窗體或控件的線程,將拋出如果您嘗試調用,則爲異常。

1

每種形式在不同的線程中運行。讓我們稱他們爲thread1和thread2。既然你想從thread1更新thread2上的東西,你需要讓這兩個線程相互通信。這就是invoke的工作

條件是檢查是否需要調用。如果你正在更新thread1本身的thread1中的字符串,那麼不需要調用,否則就是。