Created
December 9, 2013 16:44
-
-
Save sixeyed/7875555 to your computer and use it in GitHub Desktop.
TaskBatcher, for batching up memory-intensive parallel tasks. See http://geekswithblogs.net/EltonStoneman/archive/2013/12/09/batching-up-memory-intensive-parallel-tasks.aspx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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