public static async Task DoAsyncWithMaxSimultaneous(IEnumerable <Func <Task> > tasks, int maxSimultaneous) { Debug.Assert(maxSimultaneous >= 1, "should allow at least one task at a time"); List <Task> currTasks = new List <Task>(); foreach (var task in tasks) { // Wait until simultaneous tasks count drops below limit. await WaitingUntillTasksCountLessThan(maxSimultaneous); // Start next task. currTasks.Add(task()); } // Wait until all tasks complete. await WaitingUntillTasksCountLessThan(1); async Task WaitingUntillTasksCountLessThan(int count) { while (currTasks.Count >= count) { await Frame.one; currTasks.RemoveAll(currTask => currTask.IsCompleted); } } }
public static void WriteToStream <T>(this List <T> data, BinaryWriter stream) where T : ISerializable, new() { Debug.Assert(data.Count > UInt16.MaxValue, "writing stream failed"); ushort size = (ushort)data.Count; stream.Write(size); data.Capacity = size; for (int q = 0; q < size; q++) { stream.Write(data[q]); } }