using System; using System.Collections.Generic; using System.Linq; namespace Fort23.Core { public class CTaskAwaitBuffer : IDisposable where T : new() { private List> _cTasks = new List>(); private List _results = new List(); public CTask[] GetTask { get { return _cTasks.ToArray(); } } private int count; private CTask CTask; private bool _isWait; public T[] GetResults() { return _results.ToArray(); } public void Clear() { _cTasks.Clear(); _isWait = false; CTask = null; count = 0; } public void AddTask(CTask icTaskResult) { _cTasks.Add(icTaskResult); if (_isWait) { count++; AwaitTask(icTaskResult); } } public async CTask> WaitAll() { _isWait = true; count += _cTasks.Count; if (count == 0) { return new List(); } CTask = CTask.Create(false); CTask[] icTaskResults = _cTasks.ToArray(); for (int i = 0; i < icTaskResults.Length; i++) { AwaitTask(icTaskResults[i]); } await CTask; return new List(_results); } public async CTask AwaitTask(CTask icTaskResult) { T result = await icTaskResult; _results.Add(result); count--; // _cTasks.Remove(icTaskResult); if (count <= 0 && _isWait) { _isWait = false; CTask cta = CTask; // if (_cTasks != null) // { // _cTasks.Clear(); // } count = 0; cta.SetResult(); } } public void Dispose() { _cTasks.Clear(); _results.Clear(); CTask = null; _isWait = false; } } }