c# - 每 3 秒显示一次程序运行时间

标签 c# asynchronous async-await stopwatch

我正在学习 C# 中的异步,并且希望每三秒显示一次程序运行时间。我有两个解决方案,但都不能完全正常工作。

解决方案1

在第一个解决方案中,我有一个调用两个方法的循环。第一个执行计算,第二个显示启动时间,可被 3 整除。

namespace Async
{
    class Program
    {
        static void Main(string[] args)
        {
            PerformLoop();

            Console.ReadLine();
        }

        public static async void PerformLoop()
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            List<Task> l = new List<Task>();
            for (int i = 0; i < 50; i++)
            {
                l.Add(AsyncCalculation(i));
                l.Add(ShowTime(Convert.ToInt32(timer.Elapsed.TotalMilliseconds)));
            }
            await Task.WhenAll(l);
            timer.Stop();

            Console.WriteLine("Total execution time: " +
                timer.Elapsed.TotalMilliseconds);
        }

        public async static Task AsyncCalculation(int i)
        {
            var result = 10 * i;
            Console.WriteLine("Calculation result: " + result);
        }

        public async static Task ShowTime(int execTime)
        {
            if (execTime % 3 == 0)
            {
                Console.WriteLine("Execution time: " + execTime);
            }
        }
    }
}

解决方案2

在第二个解决方案中,我在循环中调用两个方法。第一个执行计算,第二个在 3 秒后显示操作时间。不幸的是,在这种情况下,第二个方法会阻止第一个方法的执行。

namespace Async
{
    class Program
    {
        static void Main(string[] args)
        {
            CallMethod();

            Console.ReadLine();
        }

        public static async void CallMethod()
        {
            for (int i = 0; i < 50; i++)
            {
                var results = Calculation(i);
                var calcResult = results.Item1;
                var time = results.Item2;

                ShowResult(calcResult);
                await ShowDelayTime(time);
            }
        }

        public static void ShowResult(int calcResult)
        {
            Console.WriteLine("Calculation result: " + calcResult);
        }

        public async static Task ShowDelayTime(int execTime)
        {
            await Task.Delay(3000);
            Console.WriteLine("Execution time: " + execTime);
        }

        public static Tuple<int, int> Calculation(int i)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            var result = 10 * i;

            stopwatch.Stop();

            return Tuple.Create(result,
                Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds));
        }
    }
}

我不知道如何连续显示计算结果并以三秒为单位显示程序的运行时间:(((

编辑

预期输出(示例):

Calculation result: 0
Calculation result: 10
Execution time: 3 seconds
Calculation result: 20
Calculation result: 30
Calculation result: 40
Execution time: 6 seconds
Calcultion result: 50
//Next iterations

程序现在显示结果,等待三秒钟,然后进入下一次迭代。我希望计算的迭代能够显示,而与时间无关(独立)。我希望程序运行时每三秒显示一次时间。

最佳答案

您可以使用 System.Threading.Timer为了每 3 秒调用一次回调,并且 Stopwatch为了测量自程序启动以来经过的秒数:

var stopwatch = Stopwatch.StartNew();
var timer = new System.Threading.Timer(_ =>
{
    Console.WriteLine($"Execution time: {stopwatch.Elapsed.TotalSeconds:#,0} seconds");
}, null, 3000, 3000);

关于c# - 每 3 秒显示一次程序运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66077941/

相关文章:

c# - 如何对第三方 API (OAuth) 进行线程安全调用?

c# - asp.net Razor 冒号运算符

c# - 如何从多个源异步加载 ASP.NET GridView?

c# - 如何停止等待任务但让任务在后台运行?

javascript - ajax内访问父对象的 `this`变量

javascript - 将 Promise 重构为 Async/await。为什么我的未定义?

c# - 如果图表数据为空,如何显示消息?

javascript - 如何使用 Selenium 滚动到元素内部的底部?

javascript - readFileSync 与在带有异步/等待的 readFile 之上使用 promisify 之间的区别

vb.net - 为什么异步函数返回 System.Threading.Tasks.Task`1[System.String]?