【发布时间】:2016-09-11 02:55:46
【问题描述】:
我有 2 个表单在不同的线程上运行。 Form2 将生成一个字符串,将其发送回 form1 并更新 form1 中的富文本框。我从朋友那里得到了代码,但我不明白其中的一部分。
你能解释一下为什么我们需要这个条件吗:
if (this.f1_rtb_01.InvokeRequired) { }
下面两行是做什么的?
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
完整代码表格1:
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();
}
}
}
【问题讨论】:
-
为什么要在两个线程上运行两个表单?
标签: c# multithreading invoke invokerequired