摘要:用 Invoke 呼叫跨執行緒的方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Invoke
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread NewThread = new Thread(new ThreadStart(NewThreadMethod)); //建立測試用的執行緒
NewThread.Start(); //啟動測試用的執行緒
}
//原執行緒,被其它執行緒呼叫
static void Method(int Param)
{
int i = Param;
}
//宣告一個委派,定義參數
delegate void MyDelegate(int Param);
//實作委派,指向員執行緒中被呼叫的Method
MyDelegate ShowData = new MyDelegate(Method);
//測試用的執行緒,在此呼叫原執行緒
void NewThreadMethod()
{
int i = 0;
while (true)
{
this.Invoke(this.ShowData, i);
Thread.Sleep(2000);
}
}
}
}