C#委托基礎系列原於2011年2月份發表在我的新浪博客中,現在將其般至本博客。
例一
[csharp]
delegate void AppendStringCallback(string text);
private void AppendString(string txt)
{
this.listView1.Items.Add(txt);
}
private void ReceiveDate()
{
AppendStringCallback appendStringCallback = new AppendStringCallback(AppendString);
this.Invoke(appendStringCallback, new object[] { string.Format("{0},{1},{2}", str1, str2
+ "號", iepAddress.ToString()) });
}
delegate void AppendStringCallback(string text);
private void AppendString(string txt)
{
this.listView1.Items.Add(txt);
}
private void ReceiveDate()
{
AppendStringCallback appendStringCallback = new AppendStringCallback(AppendString);
this.Invoke(appendStringCallback, new object[] { string.Format("{0},{1},{2}", str1, str2
+ "號", iepAddress.ToString()) });
}
例二
[csharp]
namespace ThreadPoolDemo
{
public partial class ThreadForm : Form
{
// 定義delegate以便Invoke時使用
private delegate void SetProgressBarValue(int value);
// 跟SetProgressBarValue委托相匹配的方法
private void SetProgressValue(int value)
{
progressBar.Value = value;
}
// 使用Invoke方法來設置進度條
private void RunWithInvoke()
{
int value = progressBar.Value;
while (value< progressBar.Maximum)
{
//如果是跨線程調用
if (InvokeRequired)
{
this.Invoke(new SetProgressBarValue(SetProgressValue), value++);
}
else
{
progressBar.Value = ++value;
}
}
}
public ThreadForm()
{
InitializeComponent();
}
private void btnInvoke_Click(object sender, EventArgs e)
{
progressBar.Value = 0;
Thread thread = new Thread(new ThreadStart(RunWithInvoke));
thread.Start();
}
}
}
namespace ThreadPoolDemo
{
public partial class ThreadForm : Form
{
// 定義delegate以便Invoke時使用
private delegate void SetProgressBarValue(int value);
// 跟SetProgressBarValue委托相匹配的方法
private void SetProgressValue(int value)
{
progressBar.Value = value;
}
// 使用Invoke方法來設置進度條
private void RunWithInvoke()
{
int value = progressBar.Value;
while (value< progressBar.Maximum)
{
//如果是跨線程調用
if (InvokeRequired)
{
this.Invoke(new SetProgressBarValue(SetProgressValue), value++);
}
else
{
progressBar.Value = ++value;
}
}
}
public ThreadForm()
{
InitializeComponent();
}
private void btnInvoke_Click(object sender, EventArgs e)
{
progressBar.Value = 0;
Thread thread = new Thread(new ThreadStart(RunWithInvoke));
thread.Start();
}
}
}