Last active
April 28, 2019 14:12
-
-
Save foofoodog/55a384cbb9569f56170c74f3f3f779d5 to your computer and use it in GitHub Desktop.
This file contains 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
async Task Main() | |
{ | |
Action<WorkItem> actionItem = (WorkItem w) => w.DoWork(); | |
var jobs = (from x in Enumerable.Range(1, 64) | |
let workItem = new WorkItem() { Id = x } | |
select new ActionItem<WorkItem>() | |
{ | |
item = workItem, | |
action = (t) => actionItem(t) | |
}).ToList(); | |
await Job<WorkItem>.Run(jobs, (done) => | |
{ | |
Console.WriteLine($"Task Id: {done.Id} is done on thread: {done.ThreadId} with result: {done.Result}."); | |
}); | |
var rpt = from x in jobs.Select(x => x.item.ThreadId) | |
group x by x into grp | |
orderby grp.Key | |
select new { Thread = grp.Key, Count = grp.Count() }; | |
rpt.Dump(); | |
} | |
public class ActionItem<T> | |
{ | |
public T item; | |
public Action<T> action; | |
} | |
public static class Job<T> | |
{ | |
public static async Task Run(IEnumerable<ActionItem<T>> jobs, Action<T> finished) | |
{ | |
var tasks = jobs.AsParallel().Select(job => | |
{ | |
return Task.Run(() => | |
{ | |
job.action(job.item); | |
return job.item; | |
}); | |
}).ToList(); | |
while (tasks.Any()) | |
{ | |
var done = await Task.WhenAny(tasks); | |
tasks.Remove(done); | |
finished(done.Result); | |
} | |
} | |
} | |
public class WorkItem | |
{ | |
public int Id; | |
public int Result; | |
public int ThreadId; | |
public void DoWork() | |
{ | |
ThreadId = Thread.CurrentThread.ManagedThreadId; | |
Result = Id * 100; | |
Thread.Sleep(125); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment