Mejor rendimiento
Número controlado de Threads por ejecución
var task1 = Task.Factory.StartNew(() =>
{
});
var task2 = Task.Factory.StartNew(() =>
{
});
Task.WaitAll(task1, task2);
Link artículo
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
//Your stuff
});
You can specify a MaxDegreeOfParallelism in a ParallelOptions parameter
------------Parallel.ForEach( listOfWebpages, new ParallelOptions { MaxDegreeOfParallelism = 4 }, webpage => { Download(webpage); } );
var tests = new[]{Task.Factory.StartNew(() => LectorBatch1()),Task.Factory.StartNew(() => LectorBatch2()),Task.Factory.StartNew(() => LectorBatch3())};Task.WaitAll(tests);
--
public static class MyExtensions { public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems) { return items.Select((item, inx) => new { item, inx }) .GroupBy(x => x.inx / maxItems) .Select(g => g.Select(x => x.item)); } }
and the usage would be:List<int> list = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; foreach(var batch in list.Batch(3)) { Console.WriteLine(String.Join(",",batch)); }
OUTPUT:0,1,2 3,4,5 6,7,8 9
Task Run queda corriendo en segundo plano
public Task<long> InsertLog(string tracking) { var task = Task<long>.Run(() => { return 0; }); return task; }
...
taskInsertLog.Wait();
taskInsertLog.Result
class Program{static void Main(string[] args){List<Minion> lMinions = GetMonions();List<Task> lTask;foreach (var item in Batch<Minion>(lMinions, 50))//recorre una lista en lotes de 50*{lTask = new List<Task>();foreach (var CurrentMinion in item){lTask.Add(Task.Factory.StartNew(() => Proceso(CurrentMinion)));}Task.WaitAll(lTask.ToArray());}Console.ReadKey();}public static void Proceso(Minion minion){Console.WriteLine("Id:"+ minion.Id + " Nombre:" + minion.Nombre + " Nacimiento:" + minion.FechaNacimiento);}public static IEnumerable<IEnumerable<T>> Batch<T>(IEnumerable<T> items, int maxItems){return items.Select((item, inx) => new { item, inx }).GroupBy(x => x.inx / maxItems).Select(g => g.Select(x => x.item));}public static List<Minion> GetMonions(){List<Minion> lMinions = new List<Minion>();for (int i = 0; i < 10000; i++){lMinions.Add(new Minion() { Id = i, Nombre = "nombre"+ i +"", FechaNacimiento = DateTime.Now });}return lMinions;}}
No hay comentarios:
Publicar un comentario