[英]how to calculate execution time of a async method in c#
所以我有一個Async方法,可以異步執行某些操作。
private async static void DoSomethingAsync (int i){}
我把它稱為循環讓我說50次。
for (int i = 0; i < 50; i++)
{
DoSomethingAsync (i);
}
在循環結束時我想計算總處理時間,我使用了秒表但是你可以想象它給了我錯誤的時間,因為它在循環之后被調用,它不會等待DoSomethingAsync完成處理。
如何告訴秒表等待DoSomethingAsync()的所有50個實例完成。 我已經看到了這個問題,但我不能在這里使用任務。
我不知道為什么你不能使用Task,我的猜測是你在Main方法或其他東西中調用它。 所以我會從那里出去。
就像Martin Ullrich說我會改變DoSomethingAsync
方法來返回一個任務:
private async static Task DoSomethingAsync(int i)
{
...
}
然后通過將方法添加到List<Task>
來創建一個執行循環的新方法:
private 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(DoSomethingAsync(i));
}
await Task.WhenAll(l);
timer.Stop();
Console.WriteLine(timer.Elapsed.TotalSeconds);
}
現在你從那里開始循環,在這種情況下, Main
方法只是在那里添加新的方法調用:
static void Main(string[] args)
{
PerformLoop();
Console.ReadLine();
}
這是使用async void
的缺點。 沒有修改被調用的方法就沒有辦法做到這一點(因此它可以調用回調,解鎖互斥鎖等)。
您可以更改您的方法以返回async Task
並創建另一個方法,只需調用此方法而無需等待,然后可以在以前需要async void
簽名的位置使用該方法。
async void
為什么? 不要這樣做,使用asnyc Task
,或ActionBlock
或ParallelFor/ForEach
。 然而,純粹為了新穎性(並且不能用作真正的量表),如果要在並行進程中計算時間,請考慮在並行方法中使用計時器並使用全局變量並使用Interlocked.Add方法方法來確保線程安全
private long CombinedMs;
...
private async static void DoSomethingAsync (int i)
{
var sw = new StopWatch();
sw.Start();
...
sw.Stop();
Interlocked.Add(ref CombinedMs,sw.ElapsedMillisecond);
}
無論如何,我認為你需要回到任務的繪圖板上......祝你好運
你可以有一個全局計數器來跟蹤消耗的時間,就像這樣。
public class YourClass
{
TimeSpan tSpan;
public void PerformOp()
{
tSpan=new TimeSpan();
for (int i = 0; i < 50; i++)
{
DoSomethingAsync (i);
}
}
private async static void DoSomethingAsync (int i)
{
Stopwatch stp = new StopWatch();
stp.Start();
//your Operation here
stp.Stop();
tSpan+=stp.Elapsed;//not the exact systax or usage but you get the idea
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.