C#委托多播、Lambda表达、多线程、任务
class Program
{ static void Main(string[] args)
{ Action<double> ops = MathOperations.Mutiply; ops += MathOperations.Squre; ops.Invoke(); } }
public class MathOperations
{
public static void Mutiply(double value)
{
Console.WriteLine("result:{0}", value * );
} public static void Squre(double value)
{
Console.WriteLine("result:{0}", Math.Pow(value, ));
}
}
改进的调用方式,防止多播中的末一个发生异常
class Program
{ static void Main(string[] args)
{ Action<double> ops = MathOperations.Mutiply; ops += MathOperations.Squre; //ops.Invoke(3); Delegate[] delegates = ops.GetInvocationList(); foreach (Action<double> d in delegates)
{
try
{
d();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
} }
} }
自C#3.0开始,就可以使用一种新语法把实现代码赋予委托:Lambda表达式。只要有委托参数
类型的地方,就可以使用Lambda表达式。前面使用匿名方法的例子可以改为使用Lambda表达式:
Func<string, string> anonDel = delegate(string para)
{
return "Hello " + para;
}; Console.WriteLine(anonDel("wilson")); Func<string, string, int, string> lambda = (string para, string para2,int count) =>
{
return "Hello " + para + para2 + count.ToString();
}; Console.WriteLine(lambda("Wilson", "Fu",)); Func<string, string, int, string> lambda2 = ( para, para2, count) =>
{
return "Hello " + para + para2 + count.ToString();
}; Console.WriteLine(lambda2("Wilson", "Fu", )); int someVal = ;
Func<int, int> f = x => x + someVal; //如果Lambda表达式只有一条语句,在方法块内就不需要花括号和return语句,因为编译器会添加一条隐式的return语句。 Console.WriteLine(f());
class Program
{
static void Main(string[] args)
{ int workCnt = ;
int allCnt = ;
ThreadPool.GetMaxThreads(out workCnt, out allCnt);
Console.WriteLine("workCnt={0}, allCnt={1}", workCnt, allCnt); for (int i = ; i < ; i++)
{
ThreadPool.QueueUserWorkItem(ThreadMain, i);
}
Thread.Sleep();
} protected static void ThreadMain(object o)
{
for (int i = ; i < ; i++)
{
Console.WriteLine("Index:{2},Loop:{0},Running in a thread.ID:{1}", i, Thread.CurrentThread.ManagedThreadId, (int)o);
Thread.Sleep();
} } }
}
连续任务
class Program
{
static void Main(string[] args)
{
Task t = new Task(Do1);
Task t2 = t.ContinueWith(Do2);
Task t3 = t.ContinueWith(Do2);
Task t4 = t.ContinueWith(Do2); t.Start(); //t.Wait();
//t2.Wait();
//t3.Wait();
//t4.Wait();
} static void Do1()
{
Console.WriteLine("Do1 Task.CurrentId={0}", Task.CurrentId);
//Thread.Sleep(20);
} static void Do2(Task t)
{
Console.WriteLine("Task {0} finished", t.Id);
Console.WriteLine("Do2 Task.CurrentId={0}", Task.CurrentId);
Console.WriteLine("clean……");
//Thread.Sleep(20);
}
}
执行任务返回结果:
class Program
{
static void Main(string[] args)
{
Task<Tuple<int, int>> t = new Task<Tuple<int, int>>(TaskWithResult, Tuple.Create<int, int>(, ));
t.Start();
Console.WriteLine(t.Result);
t.Wait();
} static Tuple<int, int> TaskWithResult(object division)
{
Tuple<int, int> div = (Tuple<int, int>)division;
int result = div.Item1 / div.Item2;
int reminder = div.Item1 % div.Item2; return Tuple.Create<int, int>(, );
}
}
并行
ParallelLoopResult res =
Parallel.For(, , i =>
{
Console.WriteLine("{0},Task:{1},Thread:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
});
Console.WriteLine(res.IsCompleted);
无序遍历
string[] data = {"a","b","c","d"};
Parallel.ForEach<string>(data, s =>
{
Console.WriteLine(s);
});
异步委托调用测试代码
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure(); //Timer timer = new Timer(new TimerCallback(GetThreadPoolInfo), null, 0, 1000); Func<int, DateTime> t = Fun3; Console.WriteLine("begin{0}", DateTime.Now);
IAsyncResult iRes = t.BeginInvoke(, null, null); for (int i = ; i < ; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Fun4));
Thread.Sleep();
}
//ThreadPool.QueueUserWorkItem(new WaitCallback(Fun4));
DateTime result = t.EndInvoke(iRes);
Console.WriteLine("EndInvoke={0}", result); //LogHelper.Log.Debug(DateTime.Now);
Console.ReadLine();
} static void GetThreadPoolInfo(object obj)
{
Console.Write("GetThreadPoolInfo:");
int workerThreads, completionPortThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
Console.WriteLine("workerThreads={0}, completionPortThreads={1}", workerThreads, completionPortThreads);
//LogHelper.Log.DebugFormat("workerThreads={0}, completionPortThreads={1}", workerThreads, completionPortThreads);
} static void Fun4(object obj)
{ for (int i = ; i < ; i++)
{
Console.WriteLine("threaid={2},i={0},Time={1}", i, DateTime.Now, Thread.CurrentThread.ManagedThreadId);
LogHelper.Log.DebugFormat("i={0},Time={1}", i, DateTime.Now);
Thread.Sleep();
}
} static void Fun1()
{
Thread.Sleep();
Console.WriteLine("Fun1");
} static void Fun2()
{
Thread.Sleep();
Console.WriteLine("Fun2");
} static DateTime Fun3(int obj)
{
DateTime now = DateTime.Now;
Thread.Sleep();
Console.WriteLine("input data:{0}, DateTime:{1}", obj, DateTime.Now);
return now;
}
}
C#委托多播、Lambda表达、多线程、任务的更多相关文章
- 使用匿名委托,Lambda简化多线程代码
使用匿名委托,Lambda简化多线程代码 .net中的线程也接触不少了.在多线程中最常见的应用莫过于有一个耗时的操作需要放到线程中去操作,而在这个线程中我们需要更新UI,这个时候就要创建一个委托了 ...
- 匿名方法、Lambda表达和自定义泛型委托以及Func、Action系统泛型委托
1.匿名方法的概念:一个方法没有具体的名称,而只有关键字delegate.方法参数.方法体.这种方法是匿名方法. 匿名方法的好处:将具体方法和委托直接关联在一起,如果我们基于委托只需要一个方法的时候, ...
- 委托、Lambda表达式、事件系列04,委托链是怎样形成的, 多播委托, 调用委托链方法,委托链异常处理
委托是多播委托,我们可以通过"+="把多个方法赋给委托变量,这样就形成了一个委托链.本篇的话题包括:委托链是怎样形成的,如何调用委托链方法,以及委托链异常处理. □ 调用返回类型为 ...
- 委托、Lambda表达式、事件系列01,委托是什么,委托的基本用法,委托的Method和Target属性
委托是一个类. namespace ConsoleApplication1 { internal delegate void MyDelegate(int val); class Program { ...
- 转载 C#匿名函数 委托和Lambda表达式
转载原出处: http://blog.csdn.net/honantic/article/details/46331875 匿名函数 匿名函数(Anonymous Function)是表示“内联”方法 ...
- 十二、C# 委托与Lambda表达式(匿名方法的另一种写法)
委托与Lambda表达式 1.委托概述 2.匿名方法 3.语句Lambda 4.表达式Lambda 5.表达式树 一.委托概述 相当于C++当中的方法指针,在C#中使用delegate 委托来 ...
- 委托与Lambda表达式
~,先不急说委托和Lambda表达式,先看两个例子再说: 1. 通过委托,为一个数字加10,如下代码: class Program { private delegate int JiSuan(int ...
- C# Note2:委托(delegate) & Lambda表达式 & 事件(event)
前言 本文主要讲述委托和Lambda表达式的基础知识,以及如何通过Lambda表达式实现委托调用,并阐述.NET如何将委托用作实现事件的方式. 参考:C#高级编程 1.什么是委托(delegate)? ...
- 深入学习C#匿名函数、委托、Lambda表达式、表达式树类型——Expression tree types
匿名函数 匿名函数(Anonymous Function)是表示“内联”方法定义的表达式.匿名函数本身及其内部没有值或者类型,但是可以转换为兼容的委托或者表达式树类型(了解详情).匿名函数转换的计算取 ...
- 委托、Lambda表达式、事件系列07,使用EventHandler委托
谈到事件注册,EventHandler是最常用的. EventHandler是一个委托,接收2个形参.sender是指事件的发起者,e代表事件参数. □ 使用EventHandler实现猜拳游戏 使用 ...
随机推荐
- unity, Additive Animtion注意事项
以下摘自官方文档:(http://docs.unity3d.com/Manual/AnimationScripting.html) Additive animations allow you to o ...
- C++ string::size_type 类型【转】
int main() { string str("Hello World!\n"); cout << "The size of " << ...
- MySQL【Update误操作】回滚(转)
前言: 继上一篇MySQL[Delete误操作]回滚之后,现在介绍下Update回滚,操作数据库时候难免会因为“大意”而误操作,需要快速恢复的话通过备份来恢复是不太可能的,因为需要还原和bi ...
- 控制DIV占满屏幕
网上找了很多帖子,希望是CSS控制的,但是在bootstrap环境下, 控制方式上有点问题.达不到想要的效果. 项目中需要实现的效果: DIV区域占满当前窗口的高度.且在ctrl+鼠标滚轮调整窗口大小 ...
- Android之Button自定义点击效果
我们在界面上经常会用到button按钮,但通常button点击后看不到点击的效果,如果用户连续点击了两次,就会报NAR错误,这样交互性就比较差了.如果我们自定义了button点击效果,比如我们点击了b ...
- mysql命令行导入sql文件
今天从windows上导出一个sql执行文件,再倒入到unbutn中,结果出现乱码,折腾7-8分钟, 解决方式 在导出mysql sql执行文件的时候,指定一下编码格式: 复制代码代码如下: mysq ...
- HTML5外包团队——技术分享:HTML5判断设备在线离线及监听网络状态变化例子
<!doctype html> <html> <head> <meta http-equiv="content-type" content ...
- LintCode "Number of Islands II"
A typical Union-Find one. I'm using a kinda Union-Find solution here. Some boiler-plate code - yeah ...
- bootstrap的datetimepicker只选择月份
本文转载自:http://blog.csdn.net/feng1603/article/details/41869523 直接上代码: //选择年月日的 startView: 2, minView: ...
- Linux From Scratch [2]
1. gcc需要的一些lib GMP:A free library for arbitrary precision arithmetic, operating on signed integers, ...