zoukankan      html  css  js  c++  java
  • AsyncEnumerableExtensions.cs z

    public static class Extensions
    {
    public static async Task ForEachAsync<T, U>(this IEnumerable<T> collection, Func<T, Task<U>> body, IObserver<U> observer = null)
    {
    foreach (var item in collection)
    {
    var res = await body(item);
    if (null != observer)
    {
    observer.OnNext(res);
    }
    }
    }
     
    public static async Task ForEachAsyncPerformance<T, U>(this IEnumerable<T> collection, Func<T, Task<U>> body, IObserver<U> observer = null)
    {
    var enumerator = collection.GetEnumerator();
     
    Task<U> task = null;
    if (enumerator.MoveNext())
    {
    task = body(enumerator.Current);
    }
    while (enumerator.MoveNext())
    {
    var item = enumerator.Current;
    var res = await task;
    task = body(item);
    if (null != observer)
    {
    observer.OnNext(res);
    }
    }
    if (null != task)
    {
    var res = await task;
    if (null != observer)
    {
    observer.OnNext(res);
    }
    }
    }
     
    public static async Task ForEachAsync<T, U>(this IEnumerable<T> collection, int parallelism, Func<T, Task<U>> body, IObserver<U> observer = null)
    {
    int inFlight = 0;
    var tasks = new HashSet<Task<U>>();
     
    foreach (var item in collection)
    {
    if (inFlight >= parallelism)
    {
    var task = await Task.WhenAny(tasks);
    tasks.Remove(task);
    inFlight--;
    if (null != observer)
    {
    observer.OnNext(task.Result);
    }
    }
     
    inFlight++;
    tasks.Add(body(item));
    }
     
    while (inFlight > 0)
    {
    var task = await Task.WhenAny(tasks);
    tasks.Remove(task);
    inFlight--;
    if (null != observer)
    {
    observer.OnNext(task.Result);
    }
    }
    }
    }
  • 相关阅读:
    经典SQL语句大全
    主键,外键,主键表,外间表
    一个不错的shell 脚本教程 入门级
    初窥Linux 之 我最常用的20条命令
    try catch finally 用法
    一个初学者对于MVC架构的理解
    第二次阶段冲刺2(6月1号)
    第二次阶段冲刺1(5月31号)
    学习进度条十三(第14周)
    学习进度条十二(第13周)
  • 原文地址:https://www.cnblogs.com/zeroone/p/3737417.html
Copyright © 2011-2022 走看看