您的位置:首页 > 其它

[2014-9-13]委托多线程

2016-05-17 20:27 309 查看
周六学习的时间。
继续学习委托,多线程。

1.简单委托的定义

delegate int MyDel(int a,int b);

MyDel myDel = new MyDel(Add); //Add方法必须和委托MyDel有相同的参数和返回值

myDel+=Add2 //多播委托

2.匿名函数

MyDel del =delegate(int a,int b){return a+b}

console.write(del(3,1))

3.lamba表达式

MyDel lamba =(a,b)=>{return a+b}

可以简写为 MyDel lamba=(a,b)=>a+b;

console.write(lamba(3,1));

4 扩展方法

写扩展方法满足:静态类,静态方法,this

示例代码:

static void Main(string[] args)
{
List<string> list = new List<string>() { "1", "2", "3", "4" };
var temp = list.findCalc(MyCalc);// 扩展方法的调用
foreach (var item in temp)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
static bool MyCalc(string str) // 方法与委托类型保持一致
{
if (int.Parse(str) >= 2)
{
return true;
}
return false;
}

扩展方法:

namespace System.Collections.Generic //注意命名空间写在List泛型集合的空间保持一致,方便调用
{
delegate bool IsOkdel<T>(T obj); //定义委托
static class fun
{
public static List<T> findCalc<T>(this List<T> list,IsOkdel<T> del) //this关键字,表示在List上面
{
List<T> result = new List<T>();
foreach (var item in list)
{
if (del(item))
{
result.Add(item);
}
}
return result;
}
}
}
5 泛型委托

Func<int,bool> del = a=> a>2 //有返回值

Action<>无返回值

List<int> myIntLst = new List<int>() { 1, 2, 3, 4, 5, 6 };

//把一个委托传递到一个方法里面去,然后在方法里面调用。判断集合满足条件的给返回
var result = myIntLst.Where(del);
foreach (var i in result)
{
Console.WriteLine(i);
}

6 带参数的线程

Thread thread = new Thread(a => //参数为一个委托
{
while (true)
{
//Thread.CurrentThread.ManagedThreadId :是CLR帮我们分配
Console.WriteLine("这是子线程在干活呢..参数值:{0}.@{1}", a, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
}
});
thread.IsBackground = true;
thread.Start(2);//传递参数

7 对前面错误的理解

线程的调度是由操作系统而定的,你设置调度的优先级为最高也是由操作系统而决定,不是安装先执行主线程而再执行别的线程。

We believe one thing,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautiful.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: