C# while timespan via Datetime and Stopwatch

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

namespace ConsoleApp435
{
    class Program
    {
        static int i = 0;
        static int j = 0;
        static void Main(string[] args)
        {
            Task t1 = Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    WhileStopwatchElapsed();
                    WhileLoopDatetime();
                }
            });           
           
            Console.ReadLine();
        }

        static void WhileStopwatchElapsed()
        {
            i = 0;
            Console.WriteLine("WhileStopwatchElapsed() started!");
            Stopwatch sw = new Stopwatch();
            sw.Start();
            while(sw.Elapsed<TimeSpan.FromSeconds(10))
            {
                i++;
            }
            string msg=$"{ DateTime.Now.ToString("yyyyMMddHHmmssffff")},in WhileStopwatchElapsed() i is {i} ";
            FileWriteMsg(msg);
            Console.WriteLine(msg);
            Console.WriteLine("WhileStopwatchElapsed() ended!");
        }

        static void WhileLoopDatetime()
        {
            j = 0;
            Console.WriteLine("WhileLoopDatetime() started!");
            var startTime = DateTime.UtcNow;
            while(DateTime.UtcNow-startTime<TimeSpan.FromSeconds(10))
            {
                j++;
            }
            string msg = $"{ DateTime.Now.ToString("yyyyMMddHHmmssffff")},in WhileLoopDatetime() j is {j}";
            FileWriteMsg(msg);
            Console.WriteLine(msg);
            Console.WriteLine("WhileLoopDatetime() ended!");
        }

        static void FileWriteMsg(string msg)
        {            
            File.AppendAllText("dt.txt", msg+Environment.NewLine);
        }
    }
}

 

C# while timespan via Datetime and Stopwatch

上一篇:教你用Illustrator快速简单的制作CCTV电视台标志


下一篇:.NET Core微服务二:Ocelot API网关