c#基础知识篇-委托Func和Action区别

Func指向的方法必须有返回值。Action指向的方法必须无返回值。

        static void TestA()
        {
            Console.WriteLine("无参无返回值方法");
            Console.WriteLine("TestA线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId);
        }

        static void TestB(int i, int j)
        {
            Console.WriteLine("有参无返回值方法");
            Console.WriteLine("TestB线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId);
        }

        static int TestC()
        {
            Thread.Sleep(1000);
            Console.WriteLine("无参有返回值方法");
            Console.WriteLine("TestC线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId);
            return 1;
        }

        static string TestD(int i, int j)
        {
            Thread.Sleep(2000);
            Console.WriteLine("有参有返回值方法");
            Console.WriteLine("TestD线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId);
            return (i + j).ToString();
        }
            Action actionA = TestA;
            actionA.BeginInvoke(null, null);

            Action<int, int> actionB = TestB;
            actionB.BeginInvoke(2, 3, null, null);

            Func<int> funC = TestC;
            IAsyncResult resultC = funC.BeginInvoke(null, null);
            while (!resultC.IsCompleted)
            {
                Console.WriteLine("线程执行中,未结束");
            }

            int valueC = funC.EndInvoke(resultC);
            Console.WriteLine("得到的值:" + valueC + ",当前线程ID:" + Thread.CurrentThread.ManagedThreadId + "");

            Func<int, int, string> funD = TestD;
            IAsyncResult resultD = funD.BeginInvoke(1, 2, null, null);
            while (!resultD.IsCompleted)
            {
                Console.WriteLine("线程执行中,未结束");
            }

            string valueD = funD.EndInvoke(resultD);
            Console.WriteLine("得到的值:" + valueD + ",当前线程ID:" + Thread.CurrentThread.ManagedThreadId + "");

            Console.WriteLine("主线程结束,当前主线程ID:" + Thread.CurrentThread.ManagedThreadId);

  

posted @ 2023-06-27 23:09  相遇就是有缘  阅读(25)  评论(0)    收藏  举报