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表达、多线程、任务的更多相关文章

  1. 使用匿名委托,Lambda简化多线程代码

    使用匿名委托,Lambda简化多线程代码   .net中的线程也接触不少了.在多线程中最常见的应用莫过于有一个耗时的操作需要放到线程中去操作,而在这个线程中我们需要更新UI,这个时候就要创建一个委托了 ...

  2. 匿名方法、Lambda表达和自定义泛型委托以及Func、Action系统泛型委托

    1.匿名方法的概念:一个方法没有具体的名称,而只有关键字delegate.方法参数.方法体.这种方法是匿名方法. 匿名方法的好处:将具体方法和委托直接关联在一起,如果我们基于委托只需要一个方法的时候, ...

  3. 委托、Lambda表达式、事件系列04,委托链是怎样形成的, 多播委托, 调用委托链方法,委托链异常处理

    委托是多播委托,我们可以通过"+="把多个方法赋给委托变量,这样就形成了一个委托链.本篇的话题包括:委托链是怎样形成的,如何调用委托链方法,以及委托链异常处理. □ 调用返回类型为 ...

  4. 委托、Lambda表达式、事件系列01,委托是什么,委托的基本用法,委托的Method和Target属性

    委托是一个类. namespace ConsoleApplication1 { internal delegate void MyDelegate(int val); class Program { ...

  5. 转载 C#匿名函数 委托和Lambda表达式

    转载原出处: http://blog.csdn.net/honantic/article/details/46331875 匿名函数 匿名函数(Anonymous Function)是表示“内联”方法 ...

  6. 十二、C# 委托与Lambda表达式(匿名方法的另一种写法)

    委托与Lambda表达式   1.委托概述 2.匿名方法 3.语句Lambda 4.表达式Lambda 5.表达式树   一.委托概述 相当于C++当中的方法指针,在C#中使用delegate 委托来 ...

  7. 委托与Lambda表达式

    ~,先不急说委托和Lambda表达式,先看两个例子再说: 1. 通过委托,为一个数字加10,如下代码: class Program { private delegate int JiSuan(int ...

  8. C# Note2:委托(delegate) & Lambda表达式 & 事件(event)

    前言 本文主要讲述委托和Lambda表达式的基础知识,以及如何通过Lambda表达式实现委托调用,并阐述.NET如何将委托用作实现事件的方式. 参考:C#高级编程 1.什么是委托(delegate)? ...

  9. 深入学习C#匿名函数、委托、Lambda表达式、表达式树类型——Expression tree types

    匿名函数 匿名函数(Anonymous Function)是表示“内联”方法定义的表达式.匿名函数本身及其内部没有值或者类型,但是可以转换为兼容的委托或者表达式树类型(了解详情).匿名函数转换的计算取 ...

  10. 委托、Lambda表达式、事件系列07,使用EventHandler委托

    谈到事件注册,EventHandler是最常用的. EventHandler是一个委托,接收2个形参.sender是指事件的发起者,e代表事件参数. □ 使用EventHandler实现猜拳游戏 使用 ...

随机推荐

  1. final,static

    如果输入参数在方法体执行过程中,强制不能被修改,那么参数类型前加final比较安全. final修饰的函数会被编译器优化,优化意味着编译器可能将该方法用内联(inline)方式载入.final修饰变量 ...

  2. 如何进行oracle capability i/o(压力测试数据库服务器i/o性能)

    一 .oracle 有关 IO 信息的相关统计函数 Oracle i/o stack包含hbas,存储相关的交换机.存储物理磁盘.那么oracle建议在应用程序部署的时候,建议去验证i/o避免存在问题 ...

  3. c# 可以设置透明度的 Panel 组件

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; u ...

  4. 【转】java int与integer的区别

    java int与integer的区别 int与integer的区别从大的方面来说就是基本数据类型与其包装类的区别: int 是基本类型,直接存数值,而integer是对象,用一个引用指向这个对象 1 ...

  5. php反射机制获取未知类的详细信息

    使用ReflectionClass就可以获取未知类的详细信息 demo: require("hello.php"); $class = new ReflectionClass(&q ...

  6. 已跳过 'cache' -- 节点处于冲突状态

    svn resolved ./cache ./cache 为冲突文件路径“cache”的冲突状态已解决

  7. 【Android】源码external/目录中在编译过程中生成的文件列表

    => external/eyes-free:   accessibilityvalidator.jar (host,share) => external/mesa3d:   libMesa ...

  8. DBA_基本Bash语法汇总(汇总)

     2014-06-26 Created By BaoXinjian

  9. Educational Codeforces Round 15 Road to Post Office

    Road to Post Office 题意: 一个人要从0走到d,可以坐车走k米,之后车就会坏,你可以修或不修,修要花t时间,坐车单位距离花费a时间,走路单位距离花费b时间,问到d的最短时间. 题解 ...

  10. 【初识】KMP算法入门(转)

    感觉写的很好,尤其是底下的公式,易懂,链接:http://www.cnblogs.com/mypride/p/4950245.html 举个例子 模式串S:a s d a s d a s d f a  ...