Added missing PMap overload for Func<Task> work actions

This commit is contained in:
Justin Swanson 2019-12-20 14:50:02 -06:00
parent a7845802bb
commit 790acec2d0

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.HashFunction.xxHash; using System.Data.HashFunction.xxHash;
using System.Diagnostics; using System.Diagnostics;
@ -611,6 +611,44 @@ namespace Wabbajack.Common
return await Task.WhenAll(tasks); return await Task.WhenAll(tasks);
} }
public static async Task PMap<TI>(this IEnumerable<TI> coll, WorkQueue queue,
Func<TI, Task> f)
{
var colllst = coll.ToList();
var remainingTasks = colllst.Count;
var tasks = colllst.Select(i =>
{
var tc = new TaskCompletionSource<bool>();
queue.QueueTask(async () =>
{
try
{
await f(i);
tc.SetResult(true);
}
catch (Exception ex)
{
tc.SetException(ex);
}
Interlocked.Decrement(ref remainingTasks);
});
return tc.Task;
}).ToList();
// To avoid thread starvation, we'll start to help out in the work queue
if (WorkQueue.WorkerThread)
while (remainingTasks > 0)
if (queue.Queue.TryTake(out var a, 500))
{
WorkQueue.AsyncLocalCurrentQueue.Value = WorkQueue.ThreadLocalCurrentQueue.Value;
await a();
}
await Task.WhenAll(tasks);
}
public static async Task PMap<TI>(this IEnumerable<TI> coll, WorkQueue queue, Action<TI> f) public static async Task PMap<TI>(this IEnumerable<TI> coll, WorkQueue queue, Action<TI> f)
{ {
await coll.PMap(queue, i => await coll.PMap(queue, i =>