• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#实现DataTable转.CSV文件发布时间:2022-07-13
下一篇:
C#反射发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap