使用委托调用的三个步骤:
1.定义一个与指定方法的格式相匹配的委托
2.创建自定义委托实例,将方法名作为构造函数的参数
3.通过调用调用委托对象的Invoke()间接调用该方法
可以通过使用内置委托action<> Fun<>委托
Action指向无返回值得方法
Fun指向有返回值的方法
后台线程调用主线程控件的方法
1.
//声明委托
private delegate bool Process
//声明事件
public event Process process;
private bool DelegateThing()
{
}
//注册委托
process+=new Process(DelegateThing);
调用
bool result=(bool)this.invoke(process);
2.匿名方法 使用Action或者Func
// 委托的简单用法
//Action<T>是无返回值的委托,Fun<T>有返回值的委托
Func<string, bool> processDelegate = new Func<string, bool>((x) =>
{
return false;
});
bool result=(bool)this.invoke(processDelegate,"null");
3.0个参数无返回值的调用可以使用更简单的方法
this.Invoke(new MethodInvoker(delegate { }));
this.Invoke(new MethodInvoker(()=>{ }));
4:在前台线程建立函数以便后台线程调用:
private delegate bool SetPos(int ipos, string vinfo);
public bool SetProgressBar(int ipos,string messags)
{
if (this.InvokeRequired)
{
SetPos setpos = new SetPos(SetProgressBar);
this.BeginInvoke(setpos, new object[] { ipos, messags });
}
else
{
DoSometing();
}
return false;
}
最笨的办法,但是可以多次调用,将显示函数独立出来:
private delegate void ShowFormGanzaoji(GanzaojiData ganzaojiData);
private ShowFormGanzaoji showFormGanzaoji;
private void ShowGanZaoji(GanzaojiData ganzaojiData)
{
if (this.InvokeRequired)
{
showFormGanzaoji = ShowGanZaoji;
this.Invoke(showFormGanzaoji, ganzaojiData);
}
else
{
object shijiwendu = ganzaojiData.ShijiWendu;
shijiwendu = (shijiwendu == null) ? "" : shijiwendu;
txtGZJshiji.Text = shijiwendu.ToString();
if (ganzaojiData.ChaowenJingbao)
PaintEllipse(panelGZJchaowen, Color.Red);
if (ganzaojiData.GanWentouJingbao)
PaintEllipse(panelGZJganwen, Color.Red);
if (ganzaojiData.GuozhaiJingbao)
PaintEllipse(panelGZJguozhai, Color.Red);
if (ganzaojiData.DianchiJiingBao)
PaintEllipse(panelGZJdianchi, Color.Red);
if (ganzaojiData.ChaowenJingbao != false || ganzaojiData.GanWentouJingbao != false || ganzaojiData.GuozhaiJingbao != false || ganzaojiData.DianchiJiingBao != false)
{
PaintEllipse(panelGZJYunXing, Color.Red);
}
}
}