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



我正在学习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);

最新更新