c# - 在C#中获取已执行任务的统计信息

标签 c# task-parallel-library task

我有以下简单代码:

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/

相关文章:

c# - 如何在运行时暂时禁用捆绑和缩小?

c# - 管理具有不同输出的任务

linux - 我想从task_struct获取执行时间

c# - 如何在Windows 10下安装svcutil.exe

c# - 内存平铺管理和大对象 C#

c# - Parallel.ForEach - 它在单核机器上运行在哪里?

c# - 如何在不阻塞当前线程的情况下发布 HTTP 请求并等待回调?

gradle - 包括未找到copySpec/同步任务Gradle

c# - 任务和 TAP 异步模式 : differences bwteewn factory. StartNew 和 TaskEx.Run

c# - 在 C# 中比较字符串和整数