2つのフォームが異なるスレッドで動作しています。 Form2は文字列を生成し、それをform1に送り、form1のrichtextboxを更新します。私は友人からコードを受け取りましたが、私はその一部を理解していません。C#Invoke、Invokerequired&Multithreadingに関する質問
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();
}
}
}
2つのスレッドで2つのフォームを実行しているのはなぜですか? –