Invoke는 C#에서 다양한 용도로 사용되며, 문맥에 따라 동작 방식이 조금씩 다릅니다. 주요 사용 사례는 델리게이트 호출, UI 스레드 호출 등이 있습니다.
using System;
class Program
{
delegate int MyDelegate(int x, int y);
static void Main()
{
MyDelegate del = Add;
// Invoke를 사용하여 메서드 실행
int result = del.Invoke(3, 5);
Console.WriteLine($"Result: {result}"); // 출력: Result: 8
// Invoke를 생략하고 호출 (동일한 결과)
result = del(3, 5);
Console.WriteLine($"Result: {result}"); // 출력: Result: 8
}
static int Add(int a, int b)
{
return a + b;
}
}
// Windows Forms
using System;
using System.Threading;
using System.Windows.Forms;
class Program : Form
{
private Label label;
public Program()
{
label = new Label { Text = "Initial Text", Dock = DockStyle.Fill };
Controls.Add(label);
// 백그라운드 스레드에서 UI 업데이트 시도
Thread backgroundThread = new Thread(UpdateLabelText);
backgroundThread.Start();
}
private void UpdateLabelText()
{
Thread.Sleep(2000); // 2초 대기
// UI 스레드에서 안전하게 업데이트
this.Invoke((MethodInvoker)delegate
{
label.Text = "Updated Text from Background Thread!";
});
}
[STAThread]
static void Main()
{
Application.Run(new Program());
}
}
| 특징 | Invoke | BeginInvoke |
|---|---|---|
| 실행 방식 | 동기적(Synchronous): 호출이 끝날 때까지 대기. | 비동기적(Asynchronous): 즉시 반환. |
| 대기 여부 | 호출이 완료될 때까지 호출자가 대기. | 호출자가 기다리지 않고 실행을 계속함. |
| 사용 예 | UI 업데이트, 즉각적인 작업 처리. | 백그라운드 작업 또는 비동기 UI 업데이트. |
using System;
using System.Threading;
using System.Windows.Forms;
class Program : Form
{
private Label label;
public Program()
{
label = new Label { Text = "Initial Text", Dock = DockStyle.Fill };
Controls.Add(label);
Thread backgroundThread = new Thread(() =>
{
Thread.Sleep(2000);
// 동기적 UI 업데이트
this.Invoke((MethodInvoker)(() => label.Text = "Updated using Invoke"));
// 비동기적 UI 업데이트
this.BeginInvoke((MethodInvoker)(() => label.Text = "Updated using BeginInvoke"));
});
backgroundThread.Start();
}
[STAThread]
static void Main()
{
Application.Run(new Program());
}
}