TaskBatcher, for batching up memory-intensive parallel tasks. See http://geekswithblogs.net/EltonStoneman/archive/2013/12/09/batching-up-memory-intensive-parallel-tasks.aspx
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
namespace Sixeyed.Framework | |
{ | |
public class TaskBatcher : IDisposable | |
{ | |
private int _batchSize; | |
private int _batchIndex = 0; | |
private List<Task> _tasks = new List<Task>(); | |
public TaskBatcher(int batchSize) | |
{ | |
_batchSize = batchSize; | |
} | |
public void Add(Action action) | |
{ | |
if (_batchIndex == _batchSize) | |
{ | |
Task.WaitAll(_tasks.ToArray()); | |
GC.Collect(); | |
_batchIndex = 0; | |
_tasks = new List<Task>(); | |
} | |
_tasks.Add(Task.Factory.StartNew(action)); | |
_batchIndex++; | |
} | |
public void Dispose() | |
{ | |
if (_batchIndex > 0) | |
{ | |
Task.WaitAll(_tasks.ToArray()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment