C# Running many async tasks the same time

前端 未结 2 1431
小鲜肉
小鲜肉 2021-01-28 18:50

I\'m kinda new to async tasks.

I\'ve a function that takes student ID and scrapes data from specific university website with the required ID.

    private         


        
2条回答
  •  庸人自扰
    2021-01-28 19:07

    This is what I ended up with based on @erdomke code:

        public static async Task ForEachParallel(
          this IEnumerable list, 
          Func action, 
          int dop)
        {
            var tasks = new List(dop);
            foreach (var item in list)
            {
                tasks.Add(action(item));
    
                while (tasks.Count >= dop)
                {
                    var completed = await Task.WhenAny(tasks).ConfigureAwait(false);
                    tasks.Remove(completed);
                }
            }
    
            // Wait for all remaining tasks.
            await Task.WhenAll(tasks).ConfigureAwait(false);
        }
    
        // usage
        await Enumerable
            .Range(1, 500)
            .ForEachParallel(i => ProcessItem(i), Environment.ProcessorCount);
    

提交回复
热议问题