[英]Show Timer while method is processing C#
我想顯示方法正在處理並返回其響應的時間(以秒為單位)。 可能將通過Tasks或Threads完成,但我實際上無法實現。 任何幫助,將不勝感激。
謝謝。
public function()
{
while(wait for getAllInformation() function is processing)
{
Console.Write("Elapsed time... "+ some timer which shows time in seconds);
}
}
您應該為此使用Microsoft的Reactive Framework。 然后,您可以簡單地執行以下操作:
public int GetAllInformationWithTimer()
{
using (Observable.Interval(TimeSpan.FromSeconds(1.0))
.Subscribe(x =>
Console.WriteLine("Elapsed Time: {0} seconds", x + 1)))
{
return GetAllInformation();
}
}
只需NuGet“ System.Reactive”即可獲取所需的庫。
像這樣:
public async Task MyMehod()
{
Task<IEnumerable<int>> infoGetTask = GetAllInformation();
Stopwatch stopwatch = Stopwatch.StartNew();
while (!infoGetTask.IsCompleted)
{
Console.Write($"Elapsed time... {Math.Round(stopwatch.Elapsed.TotalSeconds, 0)}");
await Task.Delay(1000);
}
foreach (int e in infoGetTask.Result)
{
Console.WriteLine(e);
}
}
public async Task<IEnumerable<int>> GetAllInformation()
{
await Task.Delay(3000);
return new int[3] { 1, 2, 3 };
}
請注意,為簡單起見,我僅檢查IsCompleted,但可以/應該檢查另外兩個可能的標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.