[C#] 匿名方法的方便和安全

        static void Main(string[] args)
        {
            int count = 5;

            //不安全写法
            Task.Run(() =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Main1_" + count);
            });
            //安全
            Test1(count);
            //安全
            Task.Factory.StartNew((c) =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Main2_" + c);
            }, count);

            //不安全
            new Action(() =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Main3_" + count);
            }).BeginInvoke(null, null);
            //安全
            new Action((c) =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Main4_" + c);
            }).BeginInvoke(count, null, null);

            count = 10;
            Console.WriteLine("ReadKey...");
            Console.ReadKey();
        }

        static void Test1(int count)
        {
            Task.Run(() =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Test_" + count);
            });
        }

你可能感兴趣的:([C#] 匿名方法的方便和安全)