C# 五十八、异步

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestCSharp
{
    delegate void myHandler(string s);
    class Program
    {
        static void Main(string[] args)
        {
            TestAsyncMechod();

            Console.ReadKey();
        }

        public static void TestAsyncMechod()
        {
            myHandler myHandler = s => { Console.WriteLine($"{s},当前线程ID:{Thread.CurrentThread.ManagedThreadId}"); };

            myHandler("直接调用");
            myHandler.Invoke("Invoke");
            myHandler.BeginInvoke("BeginInvoke", null, null);
        }
    }
}

--->
直接调用,当前线程ID:1
Invoke,当前线程ID:1
BeginInvoke,当前线程ID:3

异步与同步区别:

1、同步运行会使界面卡住,异步则不会。因为异步启动了子线程执行任务,主线程得到释放。

2、同步相对慢,异步则较快。因为异步启动了多个线程执行任务,占用了更多资源。

3、异步是无序的,因为线程的启动和执行是由操作系统决定的,是无序的。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestCSharp
{
    delegate void myHandler(int a);
    class Program
    {
        static void Main(string[] args)
        {
            //TestMechod();
            //TestAsyncMechod();

            Console.ReadKey();
        }

        public static void TestAsyncMechod()//异步
        {                       
            for (int i = 0; i < 5; i++)
            {
                myHandler myHandler = Test;
                myHandler.BeginInvoke(i, null, null);
            }          
        }

        public static void TestMechod()//同步
        {
            for (int i = 0; i < 5; i++)
            {
                myHandler myHandler = Test;
                myHandler(i);
            }
        }

        public static void Test(int num)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            long a = 0;
            for (int i = 0; i < 100000000; i++)
            {
                a += i;
            }
            stopwatch.Stop();
            Console.WriteLine("执行:{0},当前线程:{1},计算结果:{2},耗时:{3}", num, Thread.CurrentThread.ManagedThreadId,a, stopwatch.ElapsedMilliseconds);
        }
    }
}

--->同步运行结果:
执行:0,当前线程:1,计算结果:4999999950000000,耗时:243
执行:1,当前线程:1,计算结果:4999999950000000,耗时:225
执行:2,当前线程:1,计算结果:4999999950000000,耗时:238
执行:3,当前线程:1,计算结果:4999999950000000,耗时:231
执行:4,当前线程:1,计算结果:4999999950000000,耗时:233

--->异步运行结果
执行:2,当前线程:7,计算结果:4999999950000000,耗时:327
执行:1,当前线程:8,计算结果:4999999950000000,耗时:336
执行:0,当前线程:3,计算结果:4999999950000000,耗时:339
执行:3,当前线程:5,计算结果:4999999950000000,耗时:339
执行:4,当前线程:4,计算结果:4999999950000000,耗时:354

猜你喜欢

转载自blog.csdn.net/NCZ9_/article/details/88842598