Lamda Action Func Thread 实例

lamda表达式

格式:( 形参列表 ) => { 函数体 }

作用:简化匿名方法的书写,可用在任何可使用匿名方法和强类型代理的地方;

 

Action是无返回值的泛型委托。

   Action 表示无参,无返回值的委托

   Action<int,string> 表示有传入参数int,string无返回值的委托

   Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托

       Action<int,int,int,int> 表示有传入4个int型参数,无返回值的委托

   Action至少0个参数,至多16个参数,无返回值。

 

Func是有返回值的泛型委托

   Func<int> 表示无参,返回值为int的委托

   Func<object,string,int> 表示传入参数为object, string 返回值为int的委托

   Func<object,string,int> 表示传入参数为object, string 返回值为int的委托

   Func<T1,T2,,T3,int> 表示传入参数为T1,T2,,T3(泛型)返回值为int的委托

   Func至少0个参数,至多16个参数,根据返回值泛型返回。必须有返回值,不可void

 

实例:

       通过Acton 分装用户方法,以两种更新界面UI  (源代码)

 

 
private void btnFunc_Click(object sender, EventArgs e)
{
var n = TestFunc((N, Q) => { return N * Q; }, 5, 6); txtResult.Text = "Func-结果是:" + n; } private void btnAction_Click(object sender, EventArgs e) { TestAtction((N, Q) => { txtResult.Text = "Action-结果" + (N * Q).ToString(); }, 5, 6); } private void btnThrend_Click(object sender, EventArgs e) { txtResult.Text = string.Empty; threadStatus = true; new Thread(() => { Dothread((n) => { this.Invoke(new Action(() => { txtResult.Text += string.Format("现在是:{0},第{1}次执行", DateTime.Now.ToString(), n.ToString()) + "\r\n"; })); }); }).Start(); } private void btnthreaddelegate_Click(object sender, EventArgs e) { txtResult.Text = string.Empty; threadStatus = true; new Thread(() => { Dothread((n) => { WriteInvoke(string.Format("现在是:{0},第{1}次执行", DateTime.Now.ToString(), n.ToString()) + "\r\n"); }); }).Start(); } public void TestAtction(Action<int, int> ac, int n, int q) { ac(n, q); } public int TestFunc(Func<int, int, int> func, int a, int b) { return func(a, b); } private static bool threadStatus; #region "线程UI委托" delegate void WriteInvokeCallBack(string msg); void WriteInvoke(string msg) { if (this.InvokeRequired) { WriteInvokeCallBack Wc = new WriteInvokeCallBack(WriteInvoke); this.Invoke(Wc, msg); } else { txtResult.Text += msg; } } #endregion private void Dothread(Action<int> ac) { lock (this) { int i = 0; while (threadStatus) { i += 1; ac(i); if (i > 100) threadStatus = false; Thread.Sleep(100); } } }
posted @ 2013-09-26 15:54  vegetable2007  阅读(278)  评论(0编辑  收藏  举报