2016-05-15 63 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中的字符串,那么不需要调用,否则就是。