C#异步:实现一个最简单的异步

异步就是方法异步执行, 这个好理解。

异步有啥用?

以前只是听说过, 也不想计较。 不过还是碰到了需要这个东西的时候。 

比如:

定时执行, 如果不用异步方法,也不用定时器,只用Thread.Sleep来间隔。

执行方法本身需要时间,这样定时的意义就变了——两次的执行时间肯定相隔不止1分钟了。

下面是实现异步最简单的一个demo:

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

namespace ConsoleApplication20
{
    class Program
    {
        public delegate void TestDelegate(string name);
        static void Main(string[] args)
        {
            TestDelegate d = Test;
            Console.WriteLine("Beginning : {0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now);
            d.BeginInvoke("小明1", null, null);
            d.BeginInvoke("小明2", null, null);
            d.BeginInvoke("小明3", null, null);
            d.BeginInvoke("小明4", null, null);
            d.BeginInvoke("小明5", null, null);
            Console.WriteLine("End       : {0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now);

            Console.Read();
        }

        static void Test(string name) 
        {
            Console.WriteLine("TestMethod: {0:yyyy-MM-dd HH:mm:ss.fff} {1}", DateTime.Now, name);
        }
    }
}

由结果可见: BeginInvoke调用时确实是异步的。


附:定时器代码

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

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Interval = 1000;
            timer.Start();

            timer.Elapsed += new ElapsedEventHandler(PrintPoint);
            Console.WriteLine("End");
            Console.Read();
        }

        static void PrintPoint(object sender, ElapsedEventArgs e) 
        {
            DateTime dtCurr = DateTime.Now;
            Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss.fff}", dtCurr);
            Thread.Sleep(2000);
            Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss.fff}_{1:yyyy-MM-dd HH:mm:ss.fff}", dtCurr, DateTime.Now);
        }
    }
}

由结果可见:定时器的事件也是异步的, 每个事件即使执行时间较长, 也不会造成下一个定时事件的延时执行。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值