C#でinvokeを使う方法は何ですか?
:
C#でInvokeメソッドを使用すると、異なるスレッド間で通信が可能で、通常はUIスレッドでUIコントロールを更新する際に使用されます。以下は簡単な例です:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void UpdateTextBox(string text)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new MethodInvoker(delegate { textBox1.Text = text; }));
}
else
{
textBox1.Text = text;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(() =>
{
UpdateTextBox("Hello from another thread!");
});
t.Start();
}
}
上記の例では、textBox1コントロールのテキストを更新するUpdateTextBoxメソッドを定義しました。button1_Clickイベントでは、新しいスレッドを作成し、その中でUpdateTextBoxメソッドを呼び出しました。UIコントロールの更新はUIスレッドで行う必要があるため、UpdateTextBoxメソッドでInvokeメソッドを使用して、textBox1のテキストをUIスレッドで更新することを確実にしました。