• C#委托多播、Lambda表达、多线程、任务


     class Program
        {
    
            static void Main(string[] args)
            {
               
                Action<double> ops = MathOperations.Mutiply;
    
                ops += MathOperations.Squre;
    
                ops.Invoke(3);
    
            }
    
          
        }
     public class MathOperations
        {
            public static void Mutiply(double value)
            {
                Console.WriteLine("result:{0}", value * 2);
            }
    
            public static void Squre(double value)
            {
                Console.WriteLine("result:{0}", Math.Pow(value, 2));
            }
        }

     改进的调用方式,防止多播中的末一个发生异常

     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(3);
                    }
                    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",35));
    
                Func<string, string, int, string> lambda2 = ( para,  para2,  count) =>
                {
                    return "Hello " + para + para2 + count.ToString();
                };
    
                Console.WriteLine(lambda2("Wilson", "Fu", 35));
    
    
                int someVal = 5;
                Func<int, int> f = x => x + someVal; //如果Lambda表达式只有一条语句,在方法块内就不需要花括号和return语句,因为编译器会添加一条隐式的return语句。
    
                Console.WriteLine(f(3));
    class Program
        {
            static void Main(string[] args)
            {
    
                int workCnt = 0;
                int allCnt = 0;
                ThreadPool.GetMaxThreads(out workCnt, out allCnt);
                Console.WriteLine("workCnt={0}, allCnt={1}", workCnt, allCnt);
    
                for (int i = 0; i < 10; i++)
                {
                    ThreadPool.QueueUserWorkItem(ThreadMain, i);
                }
                Thread.Sleep(3000);
            }
    
    
            protected static void ThreadMain(object o)
            {
                for (int i = 0; i < 3; i++)
                {
                    Console.WriteLine("Index:{2},Loop:{0},Running in a thread.ID:{1}", i, Thread.CurrentThread.ManagedThreadId, (int)o);
                    Thread.Sleep(80);
                }
    
            }
    
        }
    }

     连续任务

    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>(8, 3));
                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>(1, 2);
            }
        }

    并行

      ParallelLoopResult res = 
                Parallel.For(0, 50, 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(12, null, null);
    
    
                for (int i = 0; i < 3000; i++)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Fun4));
                    Thread.Sleep(200);
                }
                //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 = 1; i < 25; 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(500);
                }
            }
    
            static void Fun1()
            {
                Thread.Sleep(1000);
                Console.WriteLine("Fun1");
            }
    
            static void Fun2()
            {
                Thread.Sleep(1500);
                Console.WriteLine("Fun2");
            }
    
            static DateTime Fun3(int obj)
            {
                DateTime now = DateTime.Now;
                Thread.Sleep(2000);
                Console.WriteLine("input data:{0}, DateTime:{1}", obj, DateTime.Now);
                return now;
            }
        }
    View Code
  • 相关阅读:
    IE 插件 Trixie 介绍
    .net开发沉淀之:HttpHandler(一)
    在Eclipse中导入已经存在的jar包
    浏览器的GreaseMonkey和Trixie插件
    为什么export>runnable jar file的launch configuration没有东西可以选择?
    SQL2008:如何解决“阻止保存要求重新创建表的更改”
    在IIS6下部署MVC2.0的注意事项
    ASP.NET 4.0中使用FreeTextBox和FCKeditor遇到安全问题警告的解决办法
    MyEclipse 设置JDK指向目录错误信息
    RHEL5.5 安装 oracle 11g
  • 原文地址:https://www.cnblogs.com/weiweictgu/p/5558626.html
Copyright © 2020-2023  润新知