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;
}
}