异步延时启动

这段代码有点绕,很搞。

class Program

    {

        public static Task<DateTimeOffset> Delay(int millisecondsTimeout)

        {

            TaskCompletionSource<DateTimeOffset> tcs = null;

            Timer timer = null;



            timer = new Timer(delegate

            {

                timer.Dispose();

                //这里插入操作
                tcs.TrySetResult(DateTimeOffset.UtcNow);

            }, null, Timeout.Infinite, Timeout.Infinite);



            tcs = new TaskCompletionSource<DateTimeOffset>(timer);

            Console.WriteLine("时间开始:" + DateTimeOffset.UtcNow);

            timer.Change(millisecondsTimeout, Timeout.Infinite);

            return tcs.Task;

        }





        static void Main(string[] args)

        {

           Task<DateTimeOffset > task =  Program.Delay(10000);

           Console.WriteLine("时间终止:"+ task.Result);

            Console.Read();

        }

    }

 

 


你可能感兴趣的:(异步)