我有以下简单代码:
var tasks = statements.Select(statement => _session.ExecuteAsync(statement));
var result = Task.WhenAll(tasks).Result;
[...]
如何计算所有已执行任务的最小值、最大值、平均值等? 任务类没有像“executedMilliseconds”这样的属性
最佳答案
使用以下扩展方法:
public static class EnumerableExtensions
{
public static IEnumerable<Task<TimedResult<TReturn>>> TimedSelect<TSource, TReturn>(
this IEnumerable<TSource> source,
Func<TSource, Task<TReturn>> func )
{
if (source == null) throw new ArgumentNullException("source");
if (func == null) throw new ArgumentNullException("func");
return source.Select(x =>
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Task<TReturn> task = func(x);
Task<TimedResult<TReturn>> timedResultTask = task
.ContinueWith(y =>
{
stopwatch.Stop();
return new TimedResult<TReturn>(task, stopwatch.Elapsed);
});
return timedResultTask;
});
}
}
public class TimedResult<T>
{
internal TimedResult(Task<T> task, TimeSpan duration)
{
Task = task;
Duration = duration;
}
public readonly Task<T> Task;
public readonly TimeSpan Duration;
}
和调用点
var tasks = statements.TimedSelect(statement => _session.ExecuteAsync(statement));
var result = Task.WhenAll(tasks).Result;
您可以提取您需要的结果
// Whatever works (ugly, but just as an example)...
var min = result.Select(x => x.Duration).Min();
var max = result.Select(x => x.Duration).Max();
var avg = new TimeSpan((long)result.Select(x => x.Duration.Ticks).Average());
请注意,这包括池等待时间(等待任务线程可用的时间),因此可能不准确。
此扩展的非通用变体是读者的练习。
关于c# - 在C#中获取已执行任务的统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366387/